将制表符转换为RichTextBox中的空格
我有一个WinForms应用程序与窗体上的RichTextBox
控件。 现在,我将AcceptsTabs
属性设置为true,以便在按Tab键时插入制表符。
我想做的是让它在命中Tab时插入4个空格而不是\t
制表符(我使用的是等宽字体)。 我怎样才能做到这一点?
添加一个新类来覆盖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
。
将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); } }