简体   繁体   中英

C# Detect when key gets pressed and trigger a button

So I'm trying to make a simple calculator. The user can only input the numbers by the buttons on the form or by the numpad. This is the code I have:

private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        string key = "";

        switch (e.KeyCode)
        {
            case (Keys.NumPad1):
                key = "1";
                break;
            case (Keys.NumPad2):
                key = "2";
                break;
            default:
                break;
        }

        txt_string.Text = txt_string.Text + key;
    }

If I make a breakpoint on the KeyDown function and press the Numpad keys (and every other keys) the program doesnt even comes to that breakpoint.

Do I have to change something on my Form to detect the Keys?

You'll need to set KeyPreview to true (property on the form). Also, I would advise against trying to debug the behaviour - because you may affect the behaviour you're testing (Debug.WriteLine()) is your friend here.

Just to point out that many keyboard doesnt have numpad. You can check if the key is a integer.

void Form1_KeyDown(object sender, KeyPressEventArgs e)
{
    if (char.IsDigit(e.KeyChar))
    {
        txt_string.Text += e.KeyChar;
    }
}

This is more a Code Review than a solution though.

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