vb .NET custom control inheriting from TextBox doesn't fire Paint event
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 requirement with an always-black Label (no multiline) and so I inherited from Label like:
Imports System.ComponentModel
Public Class LabelDisabled
Inherits Label
Sub New()
InitializeComponent()
Enabled = False
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
' always draw it black
e.Graphics.DrawString(Me.Text, Me.Font, Brushes.Black, 0, 0)
End Sub
End Class
That works fine. Now I want the same thing but with a multiline label, so I chose to inherit from TextBox:
Imports System.ComponentModel
Public Class CustomControl1
Inherits TextBox
Sub New()
InitializeComponent()
'Paint never fires anyway
'Enabled = False
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.开发者_JAVA百科Font, brush, 0, 0)
End Sub
End Class
Now the Paint event is never fired in the CustomControl1 - TextBox inherited - control.
Why can't I get the Paint event?
Also, if I want to make the Enabled property invisible and not-settable by the user, I do:
<Browsable(False),
DefaultValue(False)>
Public Overloads Property Enabled As Boolean
Get
Return False
End Get
Set(ByVal value As Boolean)
End Set
End Property
But this way, neither I can set the "real" Enabled property, I mean the backing field.
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
精彩评论