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

transparent textbox not showing text after i leave the textbox

我为透明文本框做了这个class

public partial class TransTextBox : TextBox
{
    public TransTextBox()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor |
                 ControlStyles.OptimizedDoubleBuffer |
                 ControlStyles.AllPaintingInWmPaint |
                 ControlStyles.ResizeRedraw |
                 ControlStyles.UserPaint, true);
        BackColor = Color.Transparent;
    }
}

但是当我离开文本框时,文本消失但仍然存在。如何解决?

你有两个选择。

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

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

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

但是如果背景颜色发生变化,则需要重新调用

您可以做的是删除 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,即使您重新绘制字符串,您的字符串也会得到两倍的 "erased"。