【问题标题】:why my custom control textbox's onpaint overided method never gets called?为什么我的自定义控件文本框的 onpaint 覆盖方法永远不会被调用?
【发布时间】:2016-09-06 09:12:30
【问题描述】:

我创建了一个自定义文本框,其边框为红色。然后我启动我的应用程序,但这个 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 的快照)?

【问题讨论】:

  • 添加自定义禁用标志毫无意义。使用 Windows 窗体 TextBox 控件已提供的 Enabled 属性。
  • 是的,你是对的,我这样做是为了其他目的。请忽略它。
  • Graphics graphics = this.CreateGraphics();这是几乎总是错误的,试图拥有一个TextBox是总是 错了。不起作用。对不起。 TextBox 是遗留的,不会让你在上面画任何持久的东西,即使你做得对..

标签: c# .net winforms textbox user-controls


【解决方案1】:

您不应该创建新的 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 窗体 TextBox 控件已提供的 Enabled 属性。

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

查看this article 以获取有关如何在 TextBox 之上绘图的代码和说明。特别是 2 部分。在页面底部的 TextBox 上绘图

【讨论】:

  • 这些都不会调用我在启动代码时覆盖的 OnPaint 方法。
  • 实际上,我需要更新我的问题。 TextBox 是一个棘手的控件,因为它处理绘画的方式。等一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 2013-07-22
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多