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

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 ; // 设置为失效
......

你可能感兴趣的:(增强文本框控件:重写Control的WndProc方法,控件失效后改变文本框背景和前景色)