C# richTextBox 过滤掉或重新映射击键

C# richTextBox filter out or remap a keystroke

使用 C#,在 Win 窗体中,过滤掉(或重新映射)richTextBox 中的击键 (Ctrl-Shift-Z) 的最简单方法是什么?我知道 CodeProject 上的各种键盘钩子项目,但它们涉及整个 类。我想使用最简单的方法,例如一个函数覆盖。原因:richTextBox 似乎以与 Ctrl-Z 相同的方式对待 Ctrl-Shift-Z,即作为撤消。我更喜欢使用 Ctrl-Shift-Z 作为重做。我尝试了"KeyDown"方法,但它似乎没有捕获击键,击键似乎被处理得比那个低。

private void richTextBox_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.Z && Control.ModifierKeys == Keys.Shift && Control.ModifierKeys == Keys.Control) {
        richTextBox.Redo();
    }
}

在您的父表单中,将 KeyPreview 属性 设置为 true,然后在表单的 KeyDown 事件中查找所需的快捷方式。

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();
        this.KeyPreview = true;
        this.KeyDown += MyForm_KeyDown;
    }

    private void MyForm_KeyDown(object sender, KeyEventArgs e)
    {
        if ((e.Modifiers & Keys.Shift) != 0 &&
            (e.Modifiers & Keys.Control) != 0 &&
            (e.KeyCode == Keys.Z))
        {
            e.Handled = true;
            richTextBox1.Redo();
        }
    }
}

类似于:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.Shift | Keys.Z)) {
    richTextBox.Redo();
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

作为 Hans Passant said in his answer, you should also check to make sure you have the form's KeyPreview 属性 为真。