Patrick
Patrick

Reputation: 2577

Stop Winform keystroke from reaching child control

I have a form that has several buttons. I have KeyPreview set to true, and I have Keydown, KeyPress, and keyup events all reading

form_keyevent(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    e.handled = true;
}

For some reason, the enter key still clicks a button that has focus. What am I missing? Is there a way around it?

Upvotes: 4

Views: 2427

Answers (3)

Mark Hall
Mark Hall

Reputation: 54552

In addition to the other answers You can add a KeyDown event handler to your form, in its KeyEventArgs there is a SuppressKeyPress property which will prevent your Keypress from being sent to the parent control.

also see this SO question for what the differences are between handled and SuppressKeyPress,

From the SuppressKeyPress Link:

Gets or sets a value indicating whether the key event should be passed on to the underlying control.

example:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode  == Keys.Enter )
        e.SuppressKeyPress = true;
}

Upvotes: 0

vgru
vgru

Reputation: 51284

Pressing the Enter key on a Form with a focused button invokes the Form.ProcessCmdKey method:

This method is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. Examples of command keys include accelerators and menu shortcuts.

You can override this method to mark the key as handled:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // if enter pressed, return 'true' to skip default handler
    if ((keyData & Keys.Return) == Keys.Return)
        return true;

    return base.ProcessCmdKey(ref msg, keyData);
}

If you only want to ignore Enter when buttons are focused, you can use something like:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // if a button is focused AND enter pressed, skip default handler
    if (this.ActiveControl is Button && (keyData & Keys.Return) == Keys.Return)
        return true;

    return base.ProcessCmdKey(ref msg, keyData);
}

Upvotes: 3

rory.ap
rory.ap

Reputation: 35318

This could be happening if your button is set as the AcceptButton property on the form. If that is the case, just clear that property.

Upvotes: 2

Related Questions