不调用TextBox OnPaint方法?

时间:2016-06-21 12:22:44

标签: c# .net winforms textbox onpaint

我使用以下代码创建文本框,但在文本框的任何情况下都不会触发paint方法。你能建议一个触发OnPaint()的解决方案吗?

public class MyTextBox : TextBox
{
    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        base.OnPaintBackground(pevent);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        ControlPaint.DrawBorder(e.Graphics,this.Bounds, Color.Red,ButtonBorderStyle.Solid);
        base.OnPaint(e);
    }

    protected override void OnTextChanged(EventArgs e)
    {
        this.Invalidate();
        this.Refresh();
        base.OnTextChanged(e);
    }
}

2 个答案:

答案 0 :(得分:14)

默认情况下不会在TextBox上调用OnPaint,除非您通过调用以下方法将其注册为自绘控件:

SetStyle(ControlStyles.UserPaint, true);

e.g。来自你的MyTextBox构造函数。

答案 1 :(得分:4)

您需要切换OnPaint

中的来电
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    ControlPaint.DrawBorder(e.Graphics, this.Bounds, Color.Red, ButtonBorderStyle.Solid);
}

base.OnPaint()像往常一样绘制TextBox。如果您在<{em> DrawBorder电话之前致电base ,则会再次通过基本实施进行重新修复。

但根据MSDNPaint不支持TextBox事件:

  

此API支持产品基础结构,不能直接在您的代码中使用   重绘控件时发生。此活动与此课程无关。

所以Ben Jackon的答案应该可以解决这个问题。