我为透明文本框创建了这个类
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
,即使您重新绘制字符串,您的字符串也会被双倍“删除”。
关于c# - 离开文本框后,透明文本框不显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34462497/