增强文本框控件:重写Control的WndProc方法,控件失效后改变文本框背景和前景色

本文介绍了如何通过重写Control的WndProc方法来改变Windows Forms中文本框控件在失效状态下的背景色和前景色,以实现自定义的视觉效果。

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace FileManager
{
    
/// <summary>
    
/// 增强型文本框控件
    
/// </summary>

    class UTextBox : TextBox 
    
{
        
/// <summary>
        
/// 失效时的字符颜色
        
/// </summary>

        [DefaultValue(typeof(Color),"Empty")]
        [Description(
"失效时的字符颜色")]
        
public Color DisableForeColor getset; }

        
/// <summary>
        
/// 失效时的背景色
        
/// </summary>

        [DefaultValue(typeof(Color), "Empty")]
        [Description(
"失效时的背景色")]
        
public Color DisableBackColor getset; }

        
/// <summary>
        
/// 重写Control的WndProc方法,控件失效后改变文本框背景和前景色
        
/// </summary>
        
/// <param name="m">Window消息</param>

        protected override void WndProc(ref Message m)
        
{
            
const int WM_PAINT = 0x000f;

            
base.WndProc(ref m);

            
if (WM_PAINT == m.Msg && !this.Enabled && m.HWnd == this.Handle)
            
{
                Graphics g 
= this.CreateGraphics();
                Rectangle rect;
                
if (Color.Empty != DisableBackColor)//设置失效时的背景色
                {
                    rect 
= new Rectangle(00base.Size.Width, base.Size.Height);
                    g.FillRectangle(
new SolidBrush(DisableBackColor), rect);
                }

                
if (Color.Empty != DisableForeColor)//失效时的字符颜色
                {
                    rect 
= new Rectangle(-11base.Size.Width, base.Size.Height);
                    g.DrawString(
base.Text, base.Font, new SolidBrush(DisableForeColor), rect);
                }

            }

        }

    }

}


 

 

......

        
private UTextBox uTextBox1;
......

            
this.uTextBox1.DisableBackColor = System.Drawing.Color.Red;//失效后的背景色
            this.uTextBox1.DisableForeColor = System.Drawing.Color.Lime;//失效后的前景色
            this.uTextBox1.Name = "uTextBox1";
......

            
this.uTextBox1.Enabled = false;//设置为失效
......
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值