c# - 离开文本框后,透明文本框不显示文本

标签 c# forms textbox

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

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/

相关文章:

c# - 将 List<Property> 转换为 JObject

java - 使用 Spring 提交表单

php - 使用 WordPress 后端从表单显示 POST 数据的最简单方法?

vba - 在 Excel/VBA 中将文本框附加到图表上的点或线

c# - 如果是 JSON.NET,我应该为可选字段设置任何属性吗

c# - 大 O 符号和算法

c# - 声明变量以在 try block 之外使用的正确方法

forms - 是否使用 Spring 形式标签?

ASP.NET/VB.NET : Iterate through multiline textbox

java - 如何通过代码编辑awt文本字段