I am trying to create some sort of license verification text box that automatically splits the user inputs into chunks separated by hyphens. My license is 25 characters long and it separated as such:
XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
I have come up with the following code to parse the user input while he is typing or through copy/paste by handling the TextChanged event of the Textbox Control like so:
public static string InsertStringAtInterval(string source, string insert, int interval)
{
StringBuilder result = new StringBuilder();
int currentPosition = 0;
while (currentPosition + interval < source.Length)
{
result.Append(source.Substring(currentPosition, interval)).Append(insert);
currentPosition += interval;
}
if (currentPosition < source.Length)
{
result.Append(source.Substring(currentPosition));
}
return result.ToString();
}
private bool bHandlingChangeEvent = false;
private void txtLicense_TextChanged(object sender, EventArgs e)
{
if (bHandlingChangeEvent == true)
return;
bHandlingChangeEvent = true;
string text = txtLicense.Text.Replace("-", "").Replace(" ","");
int nPos = txtLicense.SelectionStart;
if((text.Length==5||text.Length==10||text.Length==15||text.Length==20) && txtLicense.Text[txtLicense.Text.Length-1]!='-')
{
txtLicense.Text += "-";
txtLicense.SelectionStart = nPos + 1;
}
if(text.Length>=25)
{
string tmp = text.Substring(0, 25);
tmp = InsertStringAtInterval(tmp, "-", 5);
txtLicense.Text = tmp;
txtLicense.SelectionStart = nPos;
}
bHandlingChangeEvent = false;
}
While this is working perfectly when I user types and pastes inside the box. My only problem is that when the user tries to delete characters from the entered key by either pressing backspace or delete.
Due to the forced hyphen insertion @ positions 5,10,15,20 once a user reaches one of these marks on a backspace press the logic above forces the hyphen addition to the string and the user cannot go beyond that.
I tried fiddling with KeyDown events but couldn't come up with anything useful. can someone help please.
I also tried using a MaskedTextbox but that thing is ugly as I don't want the mask/hyphens to be visible on focus and I certainly don't want to replace the prompt with white spaces as it will give some confusion when clicking inside the box as the cursor will not always position at the beginning of the box when its "supposedly" empty.