解决TextBox的Disabled字体为灰色的问题

本文介绍了一种解决Windows Form控件在禁用状态时文本颜色变灰的问题的方法。通过继承TextBox并重写OnPaint及OnEnabledChanged方法,可以在禁用状态下使文本颜色保持不变,同时确保密码显示和文本对齐等特性正常工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家一定注意到这个问题: 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值