简体   繁体   English

KeyDown KeyEventArgs无法正常工作

[英]KeyDown KeyEventArgs won't work

I am trying to include HotKeys in my program but I don't know how to execute this code: 我试图将HotKeys包含在程序中,但是我不知道如何执行此代码:

    private void Form_KeyDown(object data, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Insert)
    {
        timer1.Stop();
    }
}

Have you bound that event? 你绑定了那个事件吗? Sounds like it is not wired up. 听起来好像没有连接好。

public Form()
{
    this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form_KeyDown);
}

You can bind event that way, or doubleclick the KeyDown event in the Properties window in Visual Studio. 您可以通过这种方式绑定事件,或者在Visual Studio的“属性”窗口中双击KeyDown事件。

If you choose the point and click way, the event will bound in the Form.Designer.cs file. 如果您选择指向和单击的方式,则该事件将绑定在Form.Designer.cs文件中。

The complete code constructor and method would look like this: 完整的代码构造函数和方法如下所示:

public Form()
{
    this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form_KeyDown);
}

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Insert)
    {
        timer1.Stop();
    }
}

Just copy&paste that code to your form (I find this usage easier) 只需将代码复制并粘贴到您的表单中(我发现这种用法比较容易)

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Insert)
    {
        timer1.Stop();
    }
}

EDIT 编辑

BTW: Don't forget to set true to KeyPreview property of the form. 顺便说一句:不要忘记将true设置为KeyPreview属性。

Per my comment: 根据我的评论:

I'm not sure about the Insert key, but you're looking for Mnemonics. 我不确定插入键,但是您正在寻找助记符。 On your form, use the "&" character before the character you want to shortcut. 在您的表单上,在您要用作快捷方式的字符之前使用“&”字符。 For example, on any button, menu, label etc... that says "Open", change the text to "&Open" and it will do what you want. 例如,在任何显示“打开”的按钮,菜单,标签等...上,将文本更改为“&Open”,它将完成您想要的操作。

Edit: Keep in mind, this binds the Alt+yourCharacter key combination, not just the single key. 编辑:请记住,这绑定了Alt + yourCharacter组合键,而不仅仅是单个键。 If you're looking specifically to do special keys (insert, F1 etc...) you will need to implement a solution from the other answers (I think @QtX's solution will do what you want) 如果您要专门执行特殊键(插入,F1等...),则需要从其他答案中实现解决方案(我认为@QtX的解决方案将满足您的要求)

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

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