EnragedTanker
EnragedTanker

Reputation: 155

Catch and process KeyPress/KeyDown without modifying text in TextBox

I currently have the following event handler which catches the Ctrl+Enter key combo in my Form code:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter && e.Control)
    {
        // Stuff
    }
}

I also have two non-ReadOnly TextBoxes in the form, one of which is multiline, while the other one isn't. Whenever I hit Ctrl+Enter, the event does get handled, but it also registers as an Enter keypress when the focus is in either TextBox. What I want to do is register the key combo without the Enter keypress modifying the text in either box. Is there any way I could go about doing this?

Upvotes: 2

Views: 1781

Answers (2)

René Vogt
René Vogt

Reputation: 43886

You should use the PreviewKeyDown event instead and set the IsInputKey property accordingly:

private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Enter && e.Control)
    {
        // Stuff
        e.IsInputKey = false;
    }
}

UPDATE: From the name of your handler, I guess you added it to the Form's KeyPress/KeyDown/PreviewKeyDown event. Instead you should register the method I showed above with each TextBox's PreviewKeyDown event.

To not destroy what already works for you, you may leave your code as it is and just add a handler to the TextBox's PreviewKeyDown event where you set IsInputKey to false for the specified keys, but don't do your // Stuff.

Upvotes: 3

NoName
NoName

Reputation: 8025

Your best choice is use ProcessCmdKey: Just add this to your Form add it will work:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.Enter))
    {
        // Stuff
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

Upvotes: 5

Related Questions