【问题标题】:Selectioncolor doesn't work within KeyPress eventSelectioncolor 在 KeyPress 事件中不起作用
【发布时间】:2015-06-09 20:34:51
【问题描述】:

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

【问题讨论】:

  • richTextBox1.Text = undoList[undoList.Count - 1]; 如果你想拥有/保留任何格式,你不能直接更改Text。如果你想管理一个撤销列表,它必须包含位置以及文本和格式。而不是设置/更改rtb.SelectedText !! - 至于您注意到的差异:它们可能来自除您的代码之外正在处理的 ^Z 。设置e.Handled = true 以防止这种情况发生!
  • @TaW 在将 e.Handled 添加到信号 ^Z 后它工作了!非常感谢。
  • 很好,但是,请注意我关于直接更改文本的警告!迟早会失败的。
  • @TaW 我一定会记住这一点。我现在使用 Rtf 而不是 Text 来保持格式,并且到目前为止效果很好。 :)

标签: c# winforms colors selection keypress


【解决方案1】:

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

【讨论】:

  • 感谢您的回答。我遇到的问题不是因为没有检测到控制键。这是因为除了我在 KeyPress 事件中的逻辑之外,ctrl+Z 仍在处理中。通过将 e.Handled 设置为 true 以指示 KeyPress 事件已处理,该问题已得到解决。我想知道在处理 Ctrl 键时使用 ProcessCmdKey 而不是 KeyPress 事件是否是一个经验法则?
  • 我会说这是您在构建自定义键盘快捷键时覆盖的方法。但如果这个假设不正确,我很高兴得到纠正。
猜你喜欢
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多