简体   繁体   中英

How to change button click event into enter event?

I'm new on C#, I made a button which makes appear another button and I want to remove the click event of this new one and change it into an enter(key) event.

Code1 Code2

When the button appears it only works when I click it but no when I press Enter.

As to your question, https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.enter?view=net-5.0

The enter event is for when keyboard or mouse enter the control (button in this case). From the sounds of your question, you are wanting to click the button when the 'Enter' key is pressed.

If this is WinForms, then you might actually want a property on the parent form called 'AcceptButton' ( https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.form.acceptbutton?view=net-5.0 ). This will make it so anytime the Enter key is hit (with the exception of controls such as a RichTextBox that accepts the return key) that button will be clicked (course you still need the button click event for the button).

Although you seem to be doing something weird in your example code image, so I'm not sure that's the correct solution for it. Instead, you need to look at maybe the Keyboard events, such as KeyPress ( https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress?view=net-5.0 ). There are several: KeyDown, KeyPress, KeyUp, and PreviewKeyDown.

Note these events require Keyboard focus on the control in question. So if add them to the button you are creating in your example code, then that button will need keyboard focus to receive the keyboard events.

Also, just FYI, if a button has keyboard focus, by default the SpaceBar will click that button for you, while the Enter key is generally reserved for clicking the Form's AcceptButton.

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