Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Making it so the Enter Key behaves as if a button has been pressed

Tags:

c#

key

enter

How do I code it so that when the enter key has been pressed it behaves as if a button on the existing form has been pressed?

Let's say the button on the form makes it so a display message of hello shows up

 private void buttonHello_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hello");
}

How do I make it so when the enter key is pressed it does the same thing (for the life of me I can't remember and it's probably really simple and I'm being really dumb)

like image 314
user2867035 Avatar asked Oct 24 '13 18:10

user2867035


4 Answers

WinForms? If yes, select the FORM. Now in the Properties Pane (bottom right of the screen by default) change the AcceptButton property to "buttonHello".

See Form.AcceptButton:

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

Here's what it looks like in the Properties Pane:

enter image description here

like image 191
Idle_Mind Avatar answered Oct 17 '22 12:10

Idle_Mind


Capture the Enter key down event, like this:

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter){
        button.PerformClick();
    }
}
like image 20
Karl Anderson Avatar answered Oct 17 '22 12:10

Karl Anderson


In your Form properties, set AcceptButton = yourButton, That's it.

like image 4
Óûth Mânē Avatar answered Oct 17 '22 11:10

Óûth Mânē


add a Key Down event handler to your form. Then check if the enter key has been pressed

private void form_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode == Keys.Enter)
        buttonHello.PerformClick();
}
like image 1
Jonesopolis Avatar answered Oct 17 '22 11:10

Jonesopolis