winforms 未调用TextBox OnPaint方法?

7uzetpgm  于 2023-05-18  发布在  其他
关注(0)|答案(3)|浏览(253)

我已经使用下面的代码创建了一个文本框,但是在文本框的任何情况下,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);
    }
}
qlckcl4x

qlckcl4x1#

默认情况下,除非您通过调用以下命令将TextBox注册为自绘制控件,否则不会在TextBox上调用OnPaint:

SetStyle(ControlStyles.UserPaint, true);

例如,从MyTextBox构造函数。

vtwuwzda

vtwuwzda2#

您需要切换OnPaint中的呼叫

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

base.OnPaint()像往常一样绘制TextBox。如果在base调用之前调用DrawBorder *,则它将再次被基本实现覆盖。
但根据documentationTextBox不支持Paint事件:
此API支持产品基础结构,不打算直接从代码中使用。
在重绘控件时发生。此事件与此类无关。
所以本·杰肯的答案应该能解决这个问题。

soat7uwm

soat7uwm3#

我所做的是在窗口收到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

相关问题