Selectioncolor在KeyPress事件中不起作用

时间:2015-06-09 20:34:52

标签: c# winforms colors selection keypress

我按下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;,预期一切正常。不知道为什么。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

您希望处理命令键( 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);
}