Selectioncolor在KeyPress事件中不起作用
本文关键字:不起作用 事件 KeyPress Selectioncolor | 更新日期: 2023-09-27 17:54:38
我试图改变一些文本的颜色时按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);
}