Search code examples
c#.netxamlwindows-8microsoft-metro

Inserting a TAB space into a TextBox


I have seen few tutorials that claim to solve this issue online but they do not work. I would like to insert a TAB space when the TAB key is pressed, into my multiline TextBox.

A dudes response from Microsoft was that, by design, Metro apps will bring focus to the next control if you press TAB inside a TextBox. Now, this would make sense, if you were pressing TAB on a Single-line TextBox. But in a multiline TextBox? Don't you think it's more likely that the user will want to insert a TAB?

And yes, I know, you can insert a TAB space in a Metro TextBox by pressing Ctrl+TAB. But that is error prone, since most of us are used to just pressing TAB, and old habbits die hard sometimes.

Here is my issue. I have a text editor feature of my app where the user may need to enter large amounts of data. And you know what people are like, they like to separate things to make their text documents more readable and it's very uncomfortable and more tedious to use Ctrl+TAB. So I would like to know if anybody can help with a workaround for this (it can't involve a RichTextBox, though)?

Also, if I manage to find a workaround, will this increase the chances of my app release being rejected by the Store?


Solution

  • Subscribe to the KeyPress event of your TextBox, capture the Tab key by inspecting the KeyCode of the pressed key, and then set the Handled property of the KeyEventArgs to true so the key isn't passed onto any other controls.

    Use SendKeys to send a "Tab" character to the TextBox to mimic the behavior of pressing "Ctrl+Tab", like you said:

    TextBox_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)
    {
          if (e.KeyCode == Keys.Tab)
          {
              e.Handled = true;
              SendKeys(^{TAB});
          }
    }
    

    The carrot (^) represents the CTRL key.