我正在寻找一个最好的方法来实现常用的Windows键盘快捷键(例如Ctrl+F, Ctrl+N)在我的Windows窗体应用程序在c#。
应用程序有一个主表单,它承载许多子表单(一次一个)。当用户按Ctrl+F时,我希望显示一个自定义搜索表单。搜索表单将依赖于应用程序中当前打开的子表单。
我在考虑在ChildForm_KeyDown事件中使用这样的东西:
if (e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control)
// Show search form
但这行不通。当你按下一个键时,事件甚至不会触发。解决方案是什么?
从主窗体,你必须:
请确保您将KeyPreview设置为true(默认为true)
添加MainForm_KeyDown(..) -通过它你可以在这里设置任何你想要的快捷方式。
此外,我在谷歌上找到了这个,我想把它分享给那些仍在寻找答案的人。(全球)
我认为你必须使用user32.dll
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
/* Note that the three lines below are not needed if you only want to register one hotkey.
* The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); // The key of the hotkey that was pressed.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed.
int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.
MessageBox.Show("Hotkey has been pressed!");
// do something
}
}
进一步阅读http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/