简体   繁体   中英

Omit action when pressing Enter on button

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?

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;

您可以使用:if(e.KeyCode == Keys.Enter){}

检查Button.IsDefault属性

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM