tags:

views:

71

answers:

1

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#

+2  A: 

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
}
Ani
how can i detect a key combination? eg. Shift+Tab?
jiewmeng
@jiewmeng: System.Windows.Input.Keyboard.Modifiers. Check my answer to your question: "How can i modify selected text/wrap content etc?"
Ani