我使用以下代码创建了一个文本框,但是在文本框的任何情况下都不会触发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);
}
}
将其注册为自绘画控件
SetStyle(ControlStyles.UserPaint, true);
例如来自 MyTextBox 构造函数。
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 支持产品基础架构,并不适合直接从您的代码中使用。
重绘控件时发生。此活动与本课程无关。所以本·杰克逊的回答应该可以解决这个问题。
消息后创建图形对象。
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