我如何捕获Keys.F1不管窗体上的集中控制? [英] How do I capture Keys.F1 regardless of the focused control on a form?

查看:125
本文介绍了我如何捕获Keys.F1不管窗体上的集中控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用KeyDown事件和一些简单的code像如果(e.Key code == Keys.F1)来捕捉F1是pressed窗体上,但如果有一些文本框的形式或者有一些作者preadsheets的基座填写表格上,然后在code以上得到无用的,什么都不做。但我想要做的事情,当用户presses F1这种形式。那么,我们如何捕获特定keydown事件就像F1对整个form..and我不想去的路线,捕捉窗体上的所有其他控件的KeyDown和它们传递到表格处理。有没有干净的方式来做到这一点?

I used KeyDown event and some simple code like if (e.KeyCode == Keys.F1) to capture F1 is pressed on a form BUT if there are some text boxes on the form or if there are some spreadsheets with Dock Fill on the form then the code above gets useless and does nothing. But I want to do something when user presses F1 on this form. so how do we capture a specific keydown event like F1 on the whole form..and I do not want to go to the route that capture the KeyDown of all other controls on the form and pass them to the Form for processing. is there any cleaner way to do this?

推荐答案

是的,确实有。正确的方法的形式,无论当前具有输入焦点的控制来处理关键事件是重写<一href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.processcmdkey.aspx"><$c$c>ProcessCmdKey你的窗体类的方法:

Yes, indeed there is. The correct way for the form to handle key events regardless of the control that currently has the input focus is to override the ProcessCmdKey method of your form class:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.F1)
    {
        MessageBox.Show("You pressed the F1 key");
        return true;    // indicate that you handled this keystroke
    }

    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData)
}

您返回来表明您处理的按键和的的希望将其在其他控件传递。如果你的执行的希望将其上的其他控件的事件处理程序通过,只返回

You return true to indicate that you handled the keystroke and don't want it to be passed on to other controls. If you do want it to be passed on to the event handlers for other controls, simply return false.

和你最好忽略了<一href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.key$p$pview.aspx"><$c$c>Key$p$pview物业。这是从VB六天不合时宜,并在.NET世界中这样做的并不是真正的preferred方式。延伸阅读:<一href="http://stackoverflow.com/questions/2386695/disadvantage-of-setting-form-key$p$pview-true">Disadvantage设定Form.Key preVIEW =真的吗?

这篇关于我如何捕获Keys.F1不管窗体上的集中控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆