当我尝试制作自定义文本框时,密码字符不起作用

Password char doesnt work when i try to make my custom TextBox

我定制了一个 TextBox 这样我就可以给它加边框,效果很好...
问题是我想将 PasswordChar 设置为 *,但这不起作用
这是我的代码:

public  class TextBoxEx : TextBox
{
    // The TextBox
    private TextBox textBox = new TextBox();

    // Border color of the textbox
    private Color borderColor = Color.Gray;

    // Ctor
    public TextBoxEx()
    {
        this.PasswordChar ='*';
        this.Paint += new PaintEventHandler(TextBoxEx_Paint);
        this.Resize += new EventHandler(TextBoxEx_Resize);
        textBox.Multiline = true;
        textBox.BorderStyle = BorderStyle.None;
        this.Controls.Add(textBox);
        this.UseSystemPasswordChar = true;

        InvalidateSize();
    }

    // Exposed properties of the textbox
    public override string Text
    {
        get { return textBox.Text; }
        set { textBox.Text = value; }
    }
    // ... Expose other properties you need...

    // The border color property
    public Color BorderColor
    {
        get { return borderColor; }
        set { borderColor = value; Invalidate(); }
    }

    // Expose the Click event for the texbox
    public event EventHandler TextBoxClick
    {
        add { textBox.Click += value; }
        remove { textBox.Click -= value; }
    }
    // ... Expose other events you need...

    private void TextBoxEx_Resize(object sender, EventArgs e)
    {
        InvalidateSize();
    }
    private void TextBoxEx_Paint(object sender, PaintEventArgs e)
    {
        ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, borderColor, ButtonBorderStyle.Solid);
    }
    private void InvalidateSize()
    {
        textBox.Size = new Size(this.Width - 2, this.Height - 2);
        textBox.Location = new Point(1, 1);
    }
}

通常当我尝试默认设置自定义控件的属性时它不起作用,例如如果我设置

this.ReadOnly=true;

这也不行。所以问题不在 PasswordChar 本身。
有人知道解决方案吗?

我要尝试一下,

private TextBox textBox = new TextBox();

...

this.Controls.Add(textBox);

以上好像是问题所在,

看起来你的阴影文本框实际上是在显示什么,

如果您需要背景中的阴影属性(并且不知道您的目标),最好创建您需要的属性。

由于 class 本身继承了 TextBox class,您不需要创建内部文本框。

考虑到这一点,您可以取出 private TextBox textBox 的声明,并将对该成员的引用替换为 this,因为 thisTextBox 的后代.

在构造函数中,您还将删除 this.Controls.Add(textBox);,因为不再有要添加的内部控件。

覆盖的 Text 属性 也可以删除,因为它不会向 TextBox 定义添加功能。

InvalidateSize 方法需要返工,因为调整 Size 成员会触发 TextBoxEx_Resize 处理程序方法,该方法再次调用 InvalidateSize 方法,最终导致WhosebugException.

最后一件事,也是一件重要的事。根据MSDN...

If the Multiline property is set to true, setting the PasswordChar property has no visual effect. When the PasswordChar property is set to true, cut, copy, and paste actions in the control using the keyboard cannot be performed, regardless of whether the Multiline property is set to true or false.

意味着如果文本框是多行的,则文本框密码字符将不会显示