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

2022/2/23 9:21:29

本文主要是介绍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



这篇关于C#WinForm中支持透明的TextBox控件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程