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();
}
}
如果此方法我使用方式有什么问题,请告诉我~
————————————————
版权声明:本文为CSDN博主「猫殷瞳」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/azuredrop/article/details/46662187

posted @ 2022-02-23 08:54  China Soft  阅读(1552)  评论(0编辑  收藏  举报