大家一定注意到这个问题: Windows Form的所有控件在Disabled的时候,文字的颜色是灰色的。(尤其是XP风格下不容易看清内容)
如下图所示:
重画以后的效果:
为了解决这个问题,通常的办法是在OnPaint里按照当前TextBox的属性,
重写文本的内容把灰色字体写成黑色(或者是当前设定的ForeColor)
重画的时候还要注意以下一些问题:
①要保持Design时设定的文本对应方式(Left,Center,Right)
②要保持密码设定的字符(PasswordChar有设定时)
③文本内容超过显示区域时,要保证能最大程度的显示文本内容
继承于System的TextBox, 重写OnPaint方法,重写OnEnableChanged()方法:
调用SetStyle方法,让控件自身在Disable下能够重画文本内容。
具体如代码:
Imports System.Windows.Forms <Drawing.ToolboxBitmap(GetType(TextBox))> _ Public Class uctlEdit Inherits System.Windows.Forms.TextBox Private objColor As Drawing.Color = Me.BackColor Protected Overrides Sub OnEnabledChanged(ByVal e As System.EventArgs) MyBase.OnEnabledChanged(e) If Not Me.Enabled Then Me.BackColor = Me.Parent.BackColor Me.SetStyle(ControlStyles.UserPaint, True) Else Me.BackColor = objColor Me.SetStyle(ControlStyles.UserPaint, False) End If Me.Invalidate() Me.RecreateHandle() End Sub Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs) MyBase.OnPaint(e) Dim strText As String = Me.Text If Me.PasswordChar <> Nothing Then strText = New String(Me.PasswordChar, Me.Text.Length) End If Dim tf As TextFormatFlags = TextFormatFlags.Default If Me.TextAlign = HorizontalAlignment.Left Then tf = TextFormatFlags.Left ElseIf Me.TextAlign = HorizontalAlignment.Right Then tf = TextFormatFlags.Right Else tf = TextFormatFlags.HorizontalCenter End If Dim rect As Drawing.Rectangle = New Drawing.Rectangle(-1, 1, e.ClipRectangle.Width, e.ClipRectangle.Height) TextRenderer.DrawText(e.Graphics, strText, Me.Font, rect, Color.Black, tf) End Sub End Class