简体   繁体   中英

How to Control Buttons via Numpad Keys in Winform?

I have this requirement that the users need to use the keyboard numpad keys to control specific button assigned to it and perform each function.

Example:

if Numpad key 0 is press then Button0 will be triggered.

Or

if(Numpad0 is pressed)
{
 //do stuff
  if (inputStatus)
        {
            txtInput.Text += btn0.Text;
        }
        else
        {
            txtInput.Text = btn0.Text;
            inputStatus = true;
        }
}
else if(Numpad1 is pressed)
{
//do stuff
}

In my form i have a split container then all Buttons are located on a group box.

Set KeyPreview to true and handle KeyDown :

private void Form_KeyDown(object sender, KeyDownEventArgs e) {
    if(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
        ((Button) this["Button" + (e.KeyCode - Keys.NumPad0).ToString()]).PerformClick();
}

I haven't tested it, but that's about how I would do it.

Add a window handler for the keydown event:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys./*numpad keys*/)
    {
        // do something such as call the click handler for your button!
        e.Handled = true;
    }
}

Or you can do it for the Form instead, You didn't specify. but the logic is the same.

And don't forget to turn KeyPreview on. Use Keys.NumPad0 , Keys.NumPad1 , etc for the number pad keys. See MSDN for the Keys Enumeration .

If you want to prevent the keys default action being performed set e.Handled = true as shown above.

Set the Form's KeyPreview to true and handle the Form.KeyDown event.

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.NumPad0)
    {
        Button0.PerformClick()
        e.Handled = true;
    }
    else if (e.KeyCode == Keys.NumPad1)
    {...}
    ...
}

By using ProcessCmdkey Solves the Problem:

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {       
           if (keyData == Keys.Numpad0)
                {
                    Numpad0.PerformClick();
                    return true;
                }

            return base.ProcessCmdKey(ref msg, keyData);
        }

Thanks

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