1

我有一个 WinForms 应用程序,RichTextBox在表单上有一个控件。现在,我将AcceptsTabs属性设置为 true,这样当Tab被点击时,它会插入一个制表符。

不过,我想做的是让它在Tab被击中时插入 4 个空格而不是\t制表符(我使用的是等宽字体)。我怎样才能做到这一点?

4

2 回答 2

7

将 AcceptsTab 属性设置为 true,只需尝试使用 KeyPress 事件:

void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) {
  if (e.KeyChar == (char)Keys.Tab) {
    e.Handled = true;
    richTextBox1.SelectedText = new string(' ', 4);
  }
}

根据您对最多每四个字符添加空格的评论,您可以尝试以下操作:

void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) {
  if (e.KeyChar == (char)Keys.Tab) {
    e.Handled = true;
    int numSpaces = 4 - ((richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexOfCurrentLine()) % 4);
    richTextBox1.SelectedText = new string(' ', numSpaces);

  }
}
于 2013-04-23T23:59:53.977 回答
2

添加一个新类来覆盖您的RichTextBox

class MyRichTextBox : RichTextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if(keyData == Keys.Tab)
        {
            SelectionLength = 0;
            SelectedText = new string(' ', 4);
            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

然后,您可以将新控件拖到表单的设计视图中:

注意:与@LarsTec 的答案不同,AcceptsTab此处不需要设置。

于 2013-04-23T23:49:03.230 回答