1. 声明系统API:
[DllImport("user32.dll", EntryPoint = "RegisterHotKey", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll", EntryPoint = "UnregisterHotKey", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
重载OnLoad,注册热键:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
WinApi.RegisterHotKey(this.Handle, 225, 0, (int)Keys.F10);
WinApi.RegisterHotKey(this.Handle, 226, 0, (int)Keys.F11);
}
在FormClosing事件中注销热键:
private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
{
WinApi.UnregisterHotKey(this.Handle, 225);
WinApi.UnregisterHotKey(this.Handle, 226);
}
重载 WndProc函数 处理热键
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case 0x0312: //这个是window消息定义的注册的热键消息
if (m.WParam.ToString().Equals("225")) //F11
{
this.buttonItem_ToolBar_电网监测_Click(null, null);
}
else if (m.WParam.ToString().Equals("226")) //F12
{
this.panel1.Visible = !this.panel1.Visible;
}
break;
}
}