透明文本框在我离开文本框后不显示文本

本文关键字:文本 显示 透明 我离开 | 更新日期: 2023-09-27 18:28:11

我为透明文本框创建了这个类

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,即使重新绘制字符串,您的字符串也会被双精度"擦除"。

您有两个选项。

您可以创建一个包含TextBoxLabel的对象,焦点进入TextBox,隐藏Label,焦点离开TextBox时显示Label。这将立即修复您当前的设置。

我更直接的方法可能是这样的:

public class TransTextBox
{
    BackColor = this.Parent.BackColor;
}

但如果背景颜色发生变化,则需要再次调用。