[英]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.NumPad0
、 Keys.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.