2010-08-23 176 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