2010-08-23 177 views
1

我想以这种方式处理tab按键:C#:向光标所在的位置添加文本

如果没有选定的文本,则在光标位置添加4个空格。如果有选定的文本,我想在每个选定行的开头添加4个空格。像什么IDE像Visual Studio一样。我该怎么做呢?

我使用WPF/C#

+3

你忘了问一个问题。 – driis 2010-08-23 14:29:21

+2

您想要在哪种类型的应用程序中处理按键? C#语言遍布全球:WPF,Windows Forms,Silverlight,Console,仅举几个例子。您的问题可能与某个特定平台相关,而非特定语言。 – 2010-08-23 14:31:11

+0

我正在寻找我的魔幻水晶球,我想你正尝试使用多线texbox,richtextbox或类似的东西... – Jonathan 2010-08-23 14:42:22

回答

2

如果这是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 
} 
+0

我如何检测组合键?例如。 Shift + Tab键? – 2010-08-25 14:20:07

+0

@jiewmeng:System.Windows.Input.Keyboard.Modifiers。检查我的问题答案:“我如何修改选定的文本/包装内容等?” – Ani 2010-08-25 14:24:29