开发者

C#: Adding text to where cursor is

开发者 https://www.devze.com 2023-01-12 13:37 出处:网络
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

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消