微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何创建可聚焦且可以处理输入的自定义控件?

如何解决如何创建可聚焦且可以处理输入的自定义控件?

我想创建自定义控件,该控件将从 Control 继承并使其可聚焦并能够处理来自键盘的输入。我设法创建控件并在其上绘制边框、背景和文本,但无法使其像文本框一样聚焦在选项卡或鼠标单击上,并在 OnKeyPress 事件中处理键盘输入。

我的代码

    public class newTextEdit : Control
    {
        private string str = "this is text";
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Point startingPoint = new Point(0,0);
            StringFormat format = new StringFormat();
            Font font = new Font(this.Font.FontFamily.Name,this.Font.Size,FontStyle.Italic);
            if (this.RightToLeft == RightToLeft.Yes)
            {
                format.LineAlignment = Stringalignment.Far;
                format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
            }

            e.Graphics.DrawRectangle(Pens.Black,this.Width - 1,this.Height - 1);
            e.Graphics.FillRectangle(Brushes.White,1,this.Width - 2,this.Height - 2);
            e.Graphics.DrawString("this is text",font,Brushes.Gray,this.ClientRectangle,format);
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            str += e.KeyChar;
        }
    }

在右下角创建控件:

Created control in right bottom corner

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。