我为透明文本框创建了这个类
public partial class TransTextBox : TextBox
{
public TransTextBox()
{
SetStyle(ControlStyles.SupportsTransparentBackColor |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
BackColor = Color.Transparent;
}
}
但当我离开文本框时,文本消失了,但仍然存在。如何修复?
您可以删除ControlStyles.OptimizedDoubleBuffer
标志,然后通过OnPaint
事件上的DrawString
重新绘制文本
类似这样的东西:
public partial class TransTextBox : TextBox {
public TransTextBox() {
SetStyle(ControlStyles.SupportsTransparentBackColor |
//ControlStyles.OptimizedDoubleBuffer | //comment this flag out
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
BackColor = Color.Transparent;
}
private void redrawText() {
using (Graphics graphics = this.CreateGraphics())
using (SolidBrush brush = new SolidBrush(this.ForeColor))
graphics.DrawString(this.Text, this.Font, brush, 1, 1); //play around with how you draw string more to suit your original
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
redrawText();
}
}
如果使用DoubleBuffer
,即使重新绘制字符串,您的字符串也会被双精度"擦除"。
您有两个选项。
您可以创建一个包含TextBox
和Label
的对象,焦点进入TextBox
,隐藏Label
,焦点离开TextBox
时显示Label
。这将立即修复您当前的设置。
我更直接的方法可能是这样的:
public class TransTextBox
{
BackColor = this.Parent.BackColor;
}
但如果背景颜色发生变化,则需要再次调用。