Search code examples
c#classpasswordscontrolscustom-controls

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


I made a custom TextBox so that I can have it bordered, that works fine...
The problem is that I want to set PasswordChar to *, and that doesn't work
Here is my code:

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);
    }
}

Generally when I try to set the properties of custom control by default it doesn't work, for example if I set

this.ReadOnly=true;

This won't work either. So the problem isn't in PasswordChar itself.
Anybody know the solution?


Solution

  • I'm going to take a stab at this:

    private TextBox textBox = new TextBox();
    
    ...
    
    this.Controls.Add(textBox);
    

    The above seems to be the problem. It seems your shadow textbox is actually what's displaying.

    If you need shadow properties in the back ground (and without really knowing your goal), probably just best creating the properties you need.