Enter button automatically clicks button without being initialized (C#/Visual Studio)

5.7k Views Asked by At

My program compiles and runs fine as long as you only use the mouse to navigate. I noticed that when I hit "Enter" it automatically registers as clicking one of my buttons in the window. I have started playing around with the "AcceptButton" property and setting it to appropriate buttons or even to "None." Nothing seems to work and it stays with it's default button it seems to has tied to "Enter." I have noticed that the buttons it's going to are the first I have defined in the code.

Long story short, I want to remove the "default" value for the Enter key to what the "AcceptButton" property actually specifies it to be.

Thanks,

Andy

2

There are 2 best solutions below

5
DROP TABLE users On

you could capture the onKeyDown event and not handle it if it is enter

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        this.YOURBUTTON.PerformClick();
    }
}
0
Metro Smurf On

Assuming the WinForm has a TextBox, set the TextBox.TabIndex to 0. Again, making the assumption that this TextBox should be the first UI Element the user interacts with.

Then, change all the buttons to have a TabIndex > 0.

Finally, update the Form.AcceptButton to be the button you want to have for the default Accept/Enter.

If there is not a TextBox or some other element that can have a lower TabIndex, then the button will be the default UI Element with focus when the form is loaded up.