C#WinForm中支持透明的TextBox控件

WinForm 的 TextBox不支持透明背景色,设置背景色透明会报错:“控件不支持透明的背景色”。
this.textBox1.BackColor = Color.Transparent;


解决方法一:(测试可用)

public class TransTextBox : RichTextBox
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr LoadLibrary(string lpFileName);

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams prams = base.CreateParams;
            if (LoadLibrary("msftedit.dll") != IntPtr.Zero)
            {
                prams.ExStyle |= 0x020; // transparent 
                prams.ClassName = "RICHEDIT50W";// TRANSTEXTBOXW
            }
            return prams;
        }
    }
}
因为是派生自RichTextBox,所以若想仿照TextBox,还需要在派生控件的构造函数中设置:

this.Multiline = false;


×另,此方法有个可能出现的问题,若此控件下存在背景图片容器(如:PictureBox),会发现输入后再删除时文字会残留:


目前我是通过给此派生控件添加事件函数来刷新界面解决的,如果有更好的方法,欢迎告诉我:

this.TextChanged += new System.EventHandler(this.TransTextBox_TextChanged);
this.LostFocus += new EventHandler(this.TransTextBox_LostFocus);
private void TransTextBox_LostFocus(object sender, EventArgs e)
{
	this.Parent.Refresh();
}

private void TransTextBox_TextChanged(object sender, EventArgs e)
{
	this.Parent.Refresh();
}


解决方法二:(测试不可用)
class TransTextBox : TextBox
{
	public TransTextBox() : base()
	{
		this.SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
		base.BackColor = System.Drawing.Color.Transparent;
		this.UpdateStyles();
	}
}
如果此方法我使用方式有什么问题,请告诉我~

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值