I am attempting to make a custom control that functions like a textbox except that instead of displaying the text, it displays star characters. It still keeps track of the text entered just doesn't display it. First off, here is my class:
public partial class PasswordBox : TextBox
{
private string _password;
public string Password { get { return _password; } }
public PasswordBox ()
{
InitializeComponent();
_password = "";
}
protected override void OnTextChanged (EventArgs e)
{
base.Text = new string('*', _password.Length);
this.Select(this.Text.Length, 0);
base.OnTextChanged(e);
}
protected override void OnPreviewKeyDown (PreviewKeyDownEventArgs e)
{
if( e.KeyCode == Keys.Back )
{
int start = this.SelectionStart;
int length = this.SelectionLength;
if( length > 0 )
{
_password = _password.Remove(start, length);
}
else if( _password.Length > 0 )
{
_password = _password.Substring(0, start - 1) + _password.Substring(start);
}
}
else if( e.KeyCode != Keys.Enter )
{
if( e.Shift.False() )
{
_password += ((char)e.KeyValue).ToString().ToLower()[0];
}
else
{
MatchCollection matches = RegexPatterns.GetMatches(((char)e.KeyValue).ToString(),"[A-Za-z0-9!@#$%^&*()_+=\\:;\"'<,>\\[\\]{}.?/-]");
if( matches.Count > 0 )
{
_password += matches[0].Value;
}
}
}
base.OnPreviewKeyDown(e);
}
}
To explain some of it, the password is stored in a global variable that can also accessed by a property. When the text changes, a string consisting of stars will be displayed of the same length as the password variable string.
I am also handling the use of the shift key separately from a regular key press because I didn't know how else to get the lowercase value and because when getting the character value of the KeyValue, it would always have extra characters when the shift key was pressed, hence the RegEx test.
The issue I am having is with the backspace functionality. It works just fine if you have nothing selected and hit the backspace key but when I have a selection and press the backspace key the space that was supposed to be removed from the password field gets filled with extraneous characters such as percent signs, double quotes, and single quotes. I must have this functionality so your knowledgeable help is needed and appreciated.