vb .NET custom control inheriting from TextBox doesn't fire Paint event

天大地大妈咪最大 提交于 2019-12-01 20:27:46

I've found a solution. It looks like a TextBox disables the Paint event even for subclasses. But you can force the WM_PAINT bit calling SetStyle:

Public Class DisabledTextBox
    Inherits TextBox

    Public Sub New()
        InitializeComponent()

        Enabled = False
        SetStyle(ControlStyles.Selectable, False)
        SetStyle(ControlStyles.UserPaint, True)

    End Sub

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
        Dim brush As New SolidBrush(Me.ForeColor)
        e.Graphics.DrawString(Me.Text, Me.Font, brush, 0, 0)
    End Sub

End Class

It works perfectly as expected :)

here is your answer:

Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    MyBase.OnPaint(e)
    e.Graphics.FillRectangle(Brushes.LightGray, Me.DisplayRectangle)
    Dim sf As New StringFormat
    sf.FormatFlags = StringFormatFlags.NoWrap
    sf.HotkeyPrefix = Drawing.Text.HotkeyPrefix.Show 'if Mnemonic property is set to true
    sf.HotkeyPrefix = Drawing.Text.HotkeyPrefix.Hide 'or none if Mnemonic property is set to false
    sf.LineAlignment = StringAlignment.Center 'horizontal alignment
    sf.Alignment = StringAlignment.Center ' vertical ...
    Dim rect As Rectangle = Me.DisplayRectangle ' this is your text bounds for setting your text alignement using StringFormat(sf)
    e.Graphics.DrawString("Something", Me.Font, Brushes.DarkOliveGreen, rect, sf)
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!