Adding an F5 Hotkey in C#

冷暖自知 提交于 2019-12-08 17:13:15

问题


I'm making a windows app (WinForms) and would like my application to call a method when the user presses F5 - this should work no matter what the user is doing but they must be using the program - I don't want to use global hooks - any ideas?


回答1:


Override the form's ProcessCmdKey on your main form and look for F5.

protected override bool ProcessCmdKey (ref Message msg, Keys keyData)
{
    bool bHandled = false;
    // switch case is the easy way, a hash or map would be better, 
    // but more work to get set up.
    switch (keyData)
    {
        case Keys.F5:
            // do whatever
            bHandled = true;
            break;
    }
    return bHandled;
}



回答2:


Check out the Form.KeyPreview property, it will allow you to trap all KeyDown, KeyUp and KeyPress events at the form level before allowing them to be processed by individual elements.

MSDN Form.KeyPreview page




回答3:


If you have only one form that can have focus, you can set the KeyPreview property of that form to true and handle the KeyPress event.

The KeyPreview property will cause the form to receive all key presses, regardless which control on the form has the input focus.



来源:https://stackoverflow.com/questions/1964298/adding-an-f5-hotkey-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!