繁体   English   中英

如何通过 Winform 中的数字键控制按钮?

[英]How to Control Buttons via Numpad Keys in Winform?

我有这个要求,用户需要使用键盘小键盘键来控制分配给它的特定按钮并执行每个 function。

例子:

如果按下 Numpad 键 0,则将触发 Button0。

或者

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
}

在我的表单中,我有一个拆分容器,然后所有按钮都位于一个组框上。

KeyPreview设置为true并处理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();
}

我还没有测试过,但这就是我将如何做到的。

为 keydown 事件添加 window 处理程序:

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;
    }
}

或者您可以改为为表单执行此操作,您没有指定。 但逻辑是一样的。

并且不要忘记打开KeyPreview 使用Keys.NumPad0Keys.NumPad1等作为数字键盘键。 有关密钥枚举,请参阅 MSDN。

如果您想阻止执行键默认操作,请设置e.Handled = true ,如上所示。

将 Form 的KeyPreview设置为true并处理Form.KeyDown事件。

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

通过使用 ProcessCmdkey 解决问题:

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

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

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM