textBox的Enable属性设为false后,默认的字体会变成灰色,这会变得模糊不清
在参考了http://topic.csdn.net/t/20051014/13/4326489.html后,对其代码进行了稍微的修正
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
//当Enable为Falses时,重绘文本,实现文本颜色正常
if (this.Enabled == false)
{
// 重新绘制文本
using (StringFormat f = new StringFormat())
{
// 水平对齐
switch (this.TextAlign)
{
case HorizontalAlignment.Center:
f.Alignment = StringAlignment.Center;
break;
case HorizontalAlignment.Right:
f.Alignment = StringAlignment.Far;
break;
case HorizontalAlignment.Left:
f.Alignment = StringAlignment.Near;
break;
default:
f.Alignment = StringAlignment.Near;
break;
}
// 垂直对齐
f.LineAlignment = System.Drawing.StringAlignment.Center;
// 设置为单行文本
f.FormatFlags = System.Drawing.StringFormatFlags.NoWrap;
// 绘制文本
using (SolidBrush b = new SolidBrush(this.ForeColor))
{
pe.Graphics.DrawString(
this.Text,
this.Font,
b,
new System.Drawing.RectangleF(
0,
0,
this.ClientSize.Width,
this.ClientSize.Height),
f);
}
}
}
}
/// <summary>
/// Enable属性变更
/// </summary>
/// <param name="e"></param>
protected override void OnEnabledChanged(EventArgs e)
{
if (this.Enabled == false)
{
SetStyle(ControlStyles.UserPaint, true);
}
else
{
SetStyle(ControlStyles.UserPaint, false);
}
base.OnEnabledChanged(e);
}