Enabled设置为False时,前景色和背景色也不改变的TextBox 并居中

本文介绍了一种自定义TextBox控件的方法,通过继承系统默认的TextBox类并重写其OnEnabledChanged和OnPaint方法,实现了当TextBox禁用时改变其显示样式的效果。

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

1.公共方法

 

    public class MyTextBox : TextBox
    {
        
protected override void OnEnabledChanged(EventArgs e)
        {
            
base.OnEnabledChanged(e);
            
//设置Enabled为False时
            if (this.Enabled)
            {
                
this.SetStyle(ControlStyles.UserPaint, false);
               
            }
            
else
                
this.SetStyle(ControlStyles.UserPaint, true);
            
//再描绘
            this.Invalidate();
        }

        
//描绘TextBox
        protected override void OnPaint(PaintEventArgs e)
        {
            
base.OnPaint(e);
            System.Drawing.Brush b 
=
                
new System.Drawing.SolidBrush(this.ForeColor);

            StringFormat sf 
= new StringFormat();
            sf.LineAlignment 
= StringAlignment.Center;
            sf.Alignment 
= StringAlignment.Center;
            
//描绘字符串
            
//e.Graphics.DrawString(this.Text, this.Font, b, -1, 1);
            e.Graphics.DrawString(this.Text, this.Font, b, this.ClientRectangle, sf);

            b.Dispose();
        }
    }

 

 

2.页面 designer.cs修改为 MyTextBox

转载于:https://www.cnblogs.com/dodui/archive/2010/12/24/1916313.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值