Selectioncolor 在 KeyPress 事件中不起作用

Selectioncolor doesn't work within KeyPress event

我正在尝试在按下 Ctrl+Z 时更改某些文本的颜色,如下所示:

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Z && (e.Control))
    {
        if (undoList.Count > 0)
        {
            ignoreChange = true;
            richTextBox1.Text = undoList[undoList.Count - 1];
            //richTextBox1.Focus();
            richTextBox1.SelectionStart = 3;
            richTextBox1.SelectionLength = 2;

            richTextBox1.SelectionColor = Color.Green;
            undoList.RemoveAt(undoList.Count - 1);

            ignoreChange = false;
        }   
    }
}

但是,所选文本不会更改其颜色。它会保持突出显示。我在 Click 事件中加入了相同的逻辑,它起作用了。另外,如果我取出 ichTextBox1.SelectionColor = Color.Green; 一切正常。不知道为什么。任何帮助,将不胜感激。

您想处理命令键 (Control),而这不会发生在标准 KeyPress 事件中。为此,您必须覆盖表单上的 ProcessCmdKey 方法。

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control|Keys.Z))
    {
        if (undoList.Count > 0)
        {
            ignoreChange = true;
            richTextBox1.Text = undoList[undoList.Count - 1];
            //richTextBox1.Focus();
            richTextBox1.SelectionStart = 3;
            richTextBox1.SelectionLength = 2;

            richTextBox1.SelectionColor = Color.Green;
            undoList.RemoveAt(undoList.Count - 1);

            ignoreChange = false;

            // Do not handle base method
            // which will revert the last action
            // that is changing the selection to green.
            return true;
        }
    }
    return base.ProcessCmdKey(ref msg, keyData);
}