[英]Converting tabs into spaces in a RichTextBox
我有一个带有RichTextBox
控件的WinForms应用程序。 现在,我将AcceptsTabs
属性设置为true,以便在单击Tab时会插入一个Tab字符。
不过我想做的是使它在单击Tab时插入4个空格而不是\\t
制表符(我使用的是等宽字体)。 我怎样才能做到这一点?
在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);
}
}
添加一个新类以覆盖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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.