[英]Windows Forms Transparent TextBox C# Existing solutions don't work
我正在一个控制台应用程序中以编程方式创建我的文本框,该应用程序可动态构建一个窗体窗口。 我正在尝试使输入框(如文本框)显示为不可见,但仍允许用户输入数据,如用户名和密码或我提供的任何其他自定义字段。 这是用于游戏启动器的,我试图使其不像Windows组件。 我在下面的帖子中尝试了一些解决方案。
编辑:如您在上面看到的,我已经引用了这不能解决我的问题。 我不使用表单设计器,因为它有删除我的代码的讨厌习惯,因为我认为“它更了解”。
因为我不使用表单设计器和InitializeComponent();
,所以“接受”的答案对我不起作用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也推荐此解决方案,但它对我不起作用。 我剩下的唯一解决方案是构建一个自定义Label类,该类将获取输入并读取关键输入,并将其添加到.Text属性中,但我不想这样做。
您链接的答案中的解决方案效果很好。 如果您不使用设计器,那就没关系了……您仍然可以使用相同的解决方案。 InitializeComponent()
是由设计器文件中的代码生成器创建的简单方法。 如果您想知道创建控件的用途(看一下信息可能很有帮助),请使用设计器创建控件,然后检查.Designer.cs
文件。
编辑:它的行为有点滑稽。 您可以覆盖OnPaint
以修复白色背景和消失的文本,请参见下文。 这不是一个“完成”的实现,游标似乎不知道该去哪里,但这应该使您朝着正确的方向前进。
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结合使用后,未绘制文本框边框。 文本框显示为边框设置为“无”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.