为什么我的自定义控件文本框的 onpaint 覆盖方法永远不会被调用?

why my custom control textbox's onpaint overided method never gets called?

我创建了一个带有红色边框的自定义文本框。然后我启动我的应用程序,但此 OnPaint 从未被调用。

我的代码是这样的:

public partial class UserControl1 : TextBox
    {
        public string disable, disableFlag;
        public string Disable 
        { 
            get 
            { 

                return disable;
            } 
            set 
            { 
                disable = value;
                disableFlag = disable;
                //OnPaint(PaintEventArgs.Empty);
            } 
        }

        public UserControl1()
        {
            InitializeComponent();
        }


        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            this.Text = "testing 1";
            if (disable == "true")
            {

                Pen redPen = new Pen(Color.Red);
                Graphics graphics = this.CreateGraphics();
                graphics.DrawRectangle(redPen, this.Location.X,
                              this.Location.Y, this.Width, this.Height);
                //  base.DrawFrame(e.Graphics);
            }
        }
    }

请告诉我问题是什么(这是 winform http://prntscr.com/ceq7x5 的快照)?

您不应创建新的 Graphics 对象。使用 e.Graphics.DrawRectangle 可以使用已经存在的 Graphics 对象在控件上绘制,如下所示:

Pen redPen = new Pen(Color.Red);
e.Graphics.DrawRectangle(redPen, this.Location.X,
                          this.Location.Y, this.Width, this.Height);

另外,在这里重复我关于禁用标志的评论。添加自定义禁用标志没有意义。使用 Windows Forms TextBox 控件已经提供的 Enabled 属性。

编辑: 请注意上面的代码在 TextBox 的情况下不起作用,因为它处理绘图的方式不同。 TextBox 基本上只是本机 Win32 TextBox 的包装器,因此您需要收听很多消息,告诉它重新绘制自己。您还需要获取设备上下文的句柄并将其转换为能够绘制的托管 Graphics 对象。

查看 this article 了解有关如何在 TextBox 上绘制的代码和说明。特别是 2 部分。在页面底部的文本框上绘图