简体   繁体   English

将键盘键分配给按钮单击 WINFORM

[英]Assign a Keyboard key to a button click WINFORM

I am developing a small application with some buttons and textbox.我正在开发一个带有一些按钮和文本框的小应用程序。 What I am having problem is assigning a keyboard key (eg F3) to a button click.我遇到的问题是将键盘键(例如 F3)分配给按钮单击。

For example if the user click the button Cash the code I wanted it's executed fine, but I want to make more easier instead clicking the button with mouse, I want the user be able to press the key on keyboard.例如,如果用户单击按钮兑现我想要执行的代码,但我想让它更容易而不是用鼠标单击按钮,我希望用户能够按下键盘上的键。 I used the keydown event, also keypress event of that button, but still nothing.我使用了keydown事件,也使用了该按钮的keypress事件,但仍然没有。

I tried this keydown event我试过这个keydown事件

          if (e.KeyCode == Keys.Enter)
        {
          btncash.PerformClick()
        }

But still nothing但还是什么都没有

Do not use F3 function button it's used by OS for activating search.不要使用 F3 function 按钮,操作系统使用它来激活搜索。 Enter key is fairs click event on focused control so do not use this also. Enter 键是焦点控件上的公平单击事件,因此也不要使用它。 Implement as suggested below.按照以下建议实施。 In your Main form在你的主要形式

Set KeyPreview to True in form load event.在表单加载事件中将 KeyPreview 设置为 True。 Add KeyDown event handler with the following code使用以下代码添加 KeyDown 事件处理程序

private void Form1_KeyDown(object sender, 
KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.H)
    {
        btncash.PerformClick();
        //btncash_Click(null, null);
    }
}

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

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