WinRT XAML, SelectionStart, and CR / LF Text Box

I use a simple multi-line TextBox in one of my Windows Store Apps , and I would like to enable the use of tab for text indents.

Since WinRT does not have the XAML AcceptsTab on the TextBox , I decided that I would have to handle it by hand when I detect a Tab key.

The problem is this: \r\n apparently being treated as one character instead of two using the SelectionStart property, and I am not getting the actual char position.

The only idea I have right now is to normalize the SelectionStart by analyzing the text and adding 1 to the SelectionStart for each of the \r\n events that I see in front of the carriage.

 public static class TextBoxExtension { public static int GetNormalizedSelectionStart(this TextBox textBox) { int occurences = 0; string source = textBox.Text; for (var index = 0; index < textBox.SelectionStart + occurences ; index++) { if (source[index] == '\r' && source[index + 1] == '\n') occurences++; } return textBox.SelectionStart + occurences; } } 

Finally, the SelectionStart reset to 0 after the manipulation, so I have to return it to the correct position, this time using the abnormal position. Here's the caller:

 if (e.Key == VirtualKey.Tab) { int cursorIndex = MainTextBox.SelectionStart; int cursorIndexNormalized = MainTextBox.GetNormalizedSelectionStart(); MainTextBox.Text = MainTextBox.Text.Insert(cursorIndexNormalized, "\t"); MainTextBox.SelectionStart = cursorIndex + 1; e.Handled = true; } 

It works, but ... did I reinvent this thing again? Is there a cleaner way to do this?

+4
source share
1 answer

It seems that you need to do "Ctrl + Tab" to actually insert a tab in the text box. So all you have to do is something like this

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

^ represents the CTRL key and TAB your tab key. Using this combination, you can use Tab in your application

0
source

All Articles