How to add / accept Tab key inside RichEditBox in Windows 8 Metro / modern app?

  • Filter
  • Time
  • Show
Clear All
new posts

    How to add / accept Tab key inside RichEditBox in Windows 8 Metro / modern app?

    Unlike the RichTextBox in the .NET framework, there is no AcceptsTab property in the RichEditBox control in the Windows Runtime. Because of this, you'll need to detect when the Tab key is pressed and handle the event yourself - because by default, focus is moved onto the next control in the application. Select the RichEditBox in your application design and from the right-side "Properties" toolbar on the bottom-right of Visual Studio, switch to Events by pressing the lightning-bolt icon near the top of the Properties toolbar. Find the KeyDown and double-click the blank text field to the right of the event in the list and add the following code within the subroutine:

    If e.Key = Windows.System.VirtualKey.Tab Then
       e.Handled = True
       Dim SelectionText As String = ""
       TextBox.Document.Selection.GetText(Windows.UI.Text.TextGetOptions.None, SelectionText)
       TextBox.Document.Selection.TypeText(vbTab + SelectionText)
    End If
    Windows.System.VirtualKey.Tab returns the integer value 9, so you can in theory have a shorter conditional statement - If e.Key = 9. The Key property contains the key value that was pressed. The Key property has a Windows.System.VirtualKey value. The VirtualKey enumeration has a long list of integer values.

    The e.Handled = True line tells the Windows Runtime to not execute the default behaviour for whatever event has fired - and will prevent the default action for the specific event that has occurred for most actions that occur that trigger the KeyDown event.

    The Selection.GetText() method fetches the selected text and stores that in the SelectionText variable. Although this line is not necessary, it means that if text is actually selected prior to the Tab key being pressed, it isn't overwritten when the Tab key is pressed. The last line within the conditional statement adds the Tab character at the point where the cursor is positioned in the RichEditBox - as the MSDN documentation says, "enters text into the selection as if someone typed it."

    Read more: