C# 自定义RichTextBox OnKeyDown覆盖不';行不通

C# 自定义RichTextBox OnKeyDown覆盖不';行不通,c#,winforms,richtextbox,C#,Winforms,Richtextbox,我有一个由RichTextBox继承的类。我覆盖了voidOnKeyDown以检查传入的选项卡,因为我不需要它们 使用断点,我看到被重写的void被调用,但它没有完成它的工作 代码如下: class ProgrammingTextBox : RichTextBox { protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.Tab) {

我有一个由RichTextBox继承的类。我覆盖了void
OnKeyDown
以检查传入的选项卡,因为我不需要它们

使用断点,我看到被重写的void被调用,但它没有完成它的工作

代码如下:

class ProgrammingTextBox : RichTextBox
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab)
        {
            // Tab was pressed, replace it with space
            e.SuppressKeyPress = true; // Don't press Tab
            for (int i = 0; i < 4; i++)
            {
                base.OnKeyDown(new KeyEventArgs(Keys.Space); // Repeat space 4 times
            }
        }
        else base.OnKeyDown(e);
    }
}
类编程文本框:RichTextBox
{
受保护的覆盖无效OnKeyDown(KeyEventArgs e)
{
if(e.KeyCode==Keys.Tab)
{
//已按Tab键,请将其替换为空格
e、 SuppressKeyPress=true;//不按Tab键
对于(int i=0;i<4;i++)
{
base.OnKeyDown(newkeyeventargs(Keys.Space);//重复空格4次
}
}
else-base.OnKeyDown(e);
}
}
想要的输出应该是带有4个空格的文本,但结果作为一个选项卡,就像没有调用
for
循环中的
OnKeyDown
调用一样


知道我该怎么做吗?

当使用
选项卡时(这不是一个普通的键-可以说,它可以被预处理并移动焦点控件),您必须覆盖另一个方法,
ProcessCmdKey

像这样的

   protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
     if (keyData == Keys.Tab) {
       //TODO: Your code here

       return true;
     }

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

OnKeyPress()上的OnKeyDown()只生成通知,它们的任务不是修改文本属性。这取决于您,请指定SelectedText属性。如下所示:

class ProgrammingTextBox : RichTextBox {
    protected override bool IsInputKey(Keys keyData) {
        if (keyData == Keys.Tab) return true;
        return base.IsInputKey(keyData);
    }
    protected override void OnKeyDown(KeyEventArgs e) {
        if (e.KeyCode == Keys.Tab) {
            const string tabtospaces = "    ";
            var hassel = this.SelectionLength > 0;
            this.SelectedText = tabtospaces;
            if (!hassel) this.SelectionStart += tabtospaces.Length;
            e.SuppressKeyPress = true;
        }
        else base.OnKeyDown(e);
    }
}

尝试使用
e.handled=false;
而不是suppress,以及
keypress
事件而不是keydown。它没有做任何事情。@HansPassant我同意这个建议,只是
AppendText
将从最后一个位置添加文本(而不是从光标)谢谢,这是我将要编辑的一些编程内容的自动完成的基础。
class ProgrammingTextBox : RichTextBox {
    protected override bool IsInputKey(Keys keyData) {
        if (keyData == Keys.Tab) return true;
        return base.IsInputKey(keyData);
    }
    protected override void OnKeyDown(KeyEventArgs e) {
        if (e.KeyCode == Keys.Tab) {
            const string tabtospaces = "    ";
            var hassel = this.SelectionLength > 0;
            this.SelectedText = tabtospaces;
            if (!hassel) this.SelectionStart += tabtospaces.Length;
            e.SuppressKeyPress = true;
        }
        else base.OnKeyDown(e);
    }
}