采用API的方式来实现。首先定义这些热键注册的API,如下代码:
[DllImport("user32")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk);
//注册热键的api
[DllImport("user32")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x0312: //这个是window消息定义的 注册的热键消息
if (m.WParam.ToString().Equals("888")) //如果是我们注册的那个热键
this.Show();
break;
}
base.WndProc(ref m);
}
如果需要注册热键,直接使用类似如下代码即可:
//注册热键(窗体句柄,热键ID,辅助键,实键)
RegisterHotKey(this.Handle, 888, 7, Keys.P);
值得注意的是,7表示Shift、Alt和Ctrl三个键的组合值。Shift的值为4,Alt的值为1,Ctrl的值为2,Windows键的值为8。如果要同时按住Shift和Alt键,则值为5。在此值7表示需要同时按住Shift、Alt和Ctrl三个键,然后按住键盘的P,才表示注册该窗体的快捷键。至于按住快捷键后,发生什么事件,则修改WndProc函数里面的代码:
if (m.WParam.ToString().Equals("888")) //如果是我们注册的那个热键
后面的。如本例中this.Show();表示按住该快捷键时将显示该窗体。