How to KeyDown event when you have buttons in your form

100 Views Asked by At

I made a program in WinForms that shows a blank screen, and then if you press Enter then something happens.. well i used this code:

 private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            label1.Visible = false;
            Colors.Start();

        }

Now when I tried to add some buttons to the blank screen, the option to click on Enter just don't work anymore... no matter what I do. and please don't earse this question, I'm kind of new in programming and I know there's alot of questions like that one, but I couldn't understand them... thanks

2

There are 2 best solutions below

0
On

Is the form's AcceptButton property assigned to a button?

If so, that could be grabbing the Enter keystroke first.

0
On

An example of the suggestion by Hans Passant:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            MessageBox.Show("Enter");
            return true; // optionally prevent further action(s) on Enter; such as Button clicks
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

Note that if you return true, then controls like the buttons will not get the Enter keystroke.