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

前端 未结 2 691
醉酒成梦
醉酒成梦 2021-01-21 00:47

I need a multiline TextBox which is always disabled, but it shouldn\'t paint itself in gray, but I want to keep its designer choosen color.

I previously had the same re

相关标签:
2条回答
  • 2021-01-21 01:15

    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
    
    0 讨论(0)
  • 2021-01-21 01:16

    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 :)

    0 讨论(0)
提交回复
热议问题