0

Is there a way to omit the (whatever) performed action on a button when the key is pressed? I already got some good inputs from SO and tried to catch the event via OnKeyPress or OnKeyDown - but I could not omit the Enter-action. I also liked the idea of disabling the Tabstop property, but as soon as I click the button the problem reoccurs.

OnKeyDown only seems to fire when "casual" keys (like a or z) are pressed, but not when Enter is hit. How can I detect it - when Enter is hit - on the button itself?

Community
  • 1
  • 1
Matthias R.
  • 441
  • 2
  • 15
  • Is this button the form's default button? – kpull1 Nov 06 '14 at 09:13
  • It's the winforms default button, but wrapped in a new class. – Matthias R. Nov 06 '14 at 09:16
  • What are you trying to achieve? `Button` is a control which suppose to be *clicked*, with mouse or by hitting Enter/Spacebar. *Omit action* sounds like a solution to untold problem and what that problem would be? – Sinatr Nov 06 '14 at 09:18
  • Based on latest edit I suppose you want to listen to keypresses for a whole window? Then use [`Form.KeyPreviw`](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx) property and **form** events. – Sinatr Nov 06 '14 at 09:20
  • I already had a look at FormKeyPreview, but I am afraid of performance issues when it comes to "observing" the whole application for pressed keys. That's why I want to exclude the Enter-action just from specific parts of the application and controls (which are primarly these buttons). – Matthias R. Nov 06 '14 at 09:23

4 Answers4

1

When you press ENTER inside a non-multiline field on a form with a default button set, the click event for this button is fired, like a click, not like a keyevent (keypress, keyup, keydown, etc).

Form.AcceptButton

Gets or sets the button on the form that is clicked when the user presses the ENTER key.

If you don't want this behaviour (or want to prevent it), maybe you should remove it as the default button. But if you need it to be default only in certain situations, you can bind/unbind it programatically:

form1.AcceptButton = btnSave;
form1.AcceptButton = null;
kpull1
  • 1,623
  • 15
  • 19
0

You can use : if(e.KeyCode == Keys.Enter){}

0

Check the Button.IsDefault property

liuzhidong
  • 538
  • 3
  • 18
0

Well, the fact that

When you press ENTER [...] the click event for this button is fired

made me think about the use of the OnMouseUp(MouseEventArgs e) method instead of OnClick(EventArgs e). I gave it a shot and it totally fits my requirements - plus: it gives me the opportunity to only exclude the wrapped buttons from said issue, not involving any other controls in my application (like Form.AcceptButton).

Thanks for all your input, which made me think about the issue from another perspective!

Matthias R.
  • 441
  • 2
  • 15