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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM