Windows Forms Transparent TextBox C# 现有解决方案不起作用

Windows Forms Transparent TextBox C# Existing solutions don't work

我正在控制台应用程序中以编程方式创建我的文本框,该应用程序动态构建表单 window。我试图让输入框(例如文本框)显示为不可见,但仍允许用户输入数据,例如用户名和密码或我提供的任何其他自定义字段。这是一个游戏启动器,我试图让它看起来不像一个 windows 组件。 我已经尝试了下面 post 中的一些解决方案。

Transparency for windows forms textbox

编辑:正如您在上面看到的,我已经指出这不能解决我的问题。我不使用表单设计器,因为它有删除我的代码的坏习惯,因为我认为 "It knows better".

接受的答案对我不起作用,因为我不使用表单设计器和 InitializeComponent(); 不起作用,它只是告诉我它不是组件的功能。 我已经走到这一步了。

using System.Windows.Forms;

namespace Launcher_Namespace
{
    public class TransparentTextBox : TextBox
    {
        public TransparentTextBox()
        {
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }
    }
}

并且在初始化字段的代码主体中

            //Initialise Inputs
            _username = new TransparentTextBox();
            _username.Bounds = new Rectangle(120, 10, 120, 21);
            _username.BackColor = Color.Transparent;
            _username.BorderStyle = 0;
            _username.Visible = false;

但是所有这一切都让我可以设置 _username.BackColor = Color.Transparent; 而不会抛出错误。输入框保持白色,没有边框。我只是想让背景透明。即使 MSDN 也推荐这个解决方案,但它对我不起作用。我剩下的唯一解决方案是构建一个自定义标签 class 来获取输入并读取关键输入并将它们添加到 .Text 属性 但我不想这样做。

您链接的答案中的解决方案工作正常。如果您不使用设计器,那没关系……您仍然可以使用相同的解决方案。 InitializeComponent() 只是一个由代码生成器在设计器文件中创建的方法。如果您想知道创建控件的作用(看看它可以提供很多信息),请使用设计器创建一个控件,然后检查 .Designer.cs 文件。

编辑: 有点搞笑。您可以覆盖 OnPaint 以修复白色背景和消失的文本,请参见下文。不是 "finished" 实现,光标似乎不知道去哪里,但这应该让你朝着正确的方向前进。

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            for (int i = 0; i < 3; i++)
            {
                var x = new UserControl1 {Location = new Point(0, i*20)};
                this.Controls.Add(x);
            }
        }
    }

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

        protected override void OnPaint(PaintEventArgs e)
        {
            var backgroundBrush = new SolidBrush(Color.Transparent);
            Graphics g = e.Graphics;
            g.FillRectangle(backgroundBrush, 0, 0, this.Width, this.Height);          
            g.DrawString(Text, Font, new SolidBrush(ForeColor), new PointF(0,0), StringFormat.GenericDefault);
        }

        public void UserControl2_OnTextChanged(object sender, EventArgs e)
        {
            Invalidate();
        }
    }
}

当我们使用 SetStyle(ControlStyles.UserPaint,true) 控件边框不绘制。我在文本框中做了这个。我的文本框边框样式是 FixedSingle,但在将 setstyle 与 UserPaint 结合使用后,文本框边框未绘制。文本框显示为边框设置为 None.