TextBox OnPaint 方法没有被调用?

问题描述 投票:0回答:3

我使用以下代码创建了一个文本框,但是在文本框的任何情况下都不会触发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);
    }
}
c# .net winforms textbox onpaint
3个回答
22
投票
默认情况下,不会在 TextBox 上调用 OnPaint,除非您通过调用 :

将其注册为自绘画控件

SetStyle(ControlStyles.UserPaint, true);

例如来自 MyTextBox 构造函数。


4
投票
您需要在

OnPaint

 中切换通话

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

base.OnPaint()

 像往常一样绘制 
TextBox
。如果您在 
DrawBorder
 调用之前调用 
base ,它会再次被基本实现覆盖。

但是根据
文档

Paint事件不受

TextBox
支持:

此 API 支持产品基础架构,并不适合直接从您的代码中使用。
重绘控件时发生。此活动与本课程无关。


所以本·杰克逊的回答应该可以解决这个问题。


1
投票

WM_PAINT

 消息后创建图形对象。

C# protected override void WndProc(ref Message m) { base.WndProc(m); switch (m.Msg) { case WM_PAINT: BackgroundText(); break; } } private void BackgroundText() { if (DesignMode) { using (Graphics G = CreateGraphics()) { TextRenderer.DrawText(G, "Project No.", new Font("Microsoft Sans Serif", 8.25), new Point(3, 1), Color.FromArgb(94, 101, 117)); } return; } if (string.IsNullOrEmpty(Text)) { using (Graphics G = CreateGraphics()) { Color tColor = FindForm.ActiveControl == this ? Color.FromArgb(94, 101, 117) : SystemColors.Window; TextRenderer.DrawText(G, "Project No.", new Font("Microsoft Sans Serif", 8.25), new Point(3, 1), tColor); } } }

VB.NET Protected Overrides Sub WndProc(ByRef m As Message) MyBase.WndProc(m) Select Case m.Msg Case WM_PAINT BackgroundText() End Select End Sub Private Sub BackgroundText() If DesignMode Then Using G As Graphics = CreateGraphics() TextRenderer.DrawText(G, "Project No.", New Font("Microsoft Sans Serif", 8.25), New Point(3, 1), Color.FromArgb(94, 101, 117)) End Using Return End If If String.IsNullOrEmpty(Text) Then Using G As Graphics = CreateGraphics() Dim tColor As Color = If(FindForm.ActiveControl Is Me, Color.FromArgb(94, 101, 117), SystemColors.Window) TextRenderer.DrawText(G, "Project No.", New Font("Microsoft Sans Serif", 8.25), New Point(3, 1), tColor) End Using End If End Sub

© www.soinside.com 2019 - 2024. All rights reserved.