Selectioncolor doesn't work within KeyPress event

48 views Asked by At

I'm trying to change the color of some text when Ctrl+Z is pressed as the following:

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;
        }   
    }
}

However, the selected text won't change its color. It would stay highlighted. I threw in the same logic in a Click event and it worked. Also, if I take out ichTextBox1.SelectionColor = Color.Green; everything works expectedly. Not sure why. Any help would be appreciated.

1

There are 1 answers

2
PiotrWolkowski On BEST ANSWER

You want to handle a command key (Control) and that won't happen in a standard KeyPress event. To do that you have to override ProcessCmdKey method on your form.

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);
}