i want to handle the tab keypress in such a way that
if there is no selected text, add 4 spaces at cursor position. if there开发者_开发知识库 is selected text, i want to add 4 spaces at the start of each selected lines. something like what ide's like visual studio does. how do i do this?
i am using WPF/C#
If this is for WPF:
textBox.AcceptsReturn = true;
textBox.AcceptsTab = false;
textBox.KeyDown += OnTextBoxKeyDown;
...
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Tab)
return;
string tabReplacement = new string(' ', 4);
string selectedTextReplacement = tabReplacement +
textBox.SelectedText.Replace(Environment.NewLine, Environment.NewLine + tabReplacement);
int selectionStart = textBox.SelectionStart;
textBox.Text = textBox.Text.Remove(selectionStart, textBox.SelectionLength)
.Insert(selectionStart, selectedTextReplacement);
e.Handled = true; // to prevent loss of focus
}
精彩评论