-1

I have a MaskedTextBox that formats text to look like (###) ###-####

After entering the first 3 digits, they like to press "TAB" to the next set. Unfortunately by pressing TAB, they are in the next field.

So my boss asked me to modify the application so that the users remain in the same field but the cursor is in the next group.

    private void maskedTextBoxHomePhone_KeyPress(object sender, KeyPressEventArgs e)
    {
        MaskedTextBox mtb = (MaskedTextBox)sender;
        if (e.KeyChar == (char)Keys.Tab)
        {
            if (mtb.TextLength == 3)
            {
                mtb.SelectionStart = 4;
            }
        }
    }

I've also tried

    private void maskedTextBoxHomePhone_KeyDown(object sender, KeyEventArgs e)
    {
        MaskedTextBox mtb = (MaskedTextBox)sender;
        if (e.KeyCode == Keys.Tab)
        {
            if (mtb.TextLength == 3)
            {
                mtb.SelectionStart = 4;
            }
        }
    }
software is fun
  • 7,286
  • 18
  • 71
  • 129

1 Answers1

0

Tabs have a special meaning, that will cause the focus to change, so the event handler won't get called.

You could work around this by using the Leave event of a text box and counting the textlength that you have stored in some local variable:

private void maskedTextBoxHomePhone_Leave(object sender, EventArgs e)
{
   if (_mtbTextLength == 3) { //change selection start and goes back to masked text box }
}

Anyway, actually I would try to convince my boss otherwise. Do you really need this? Tabs are always used to change fields, you can get your users confused.

Another option would be to change the Tab behaviour by overriding the ProcessCmdKey:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
  if (keyData == Keys.Tab)
  {
      //Do something
  }
}
Henrique Forlani
  • 1,325
  • 9
  • 22