在MainForm中申明函数
MainForm()
{
[System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数
public static extern bool RegisterHotKey(
IntPtr hWnd, // handle to window
int id, // hot key identifier
uint fsModifiers, // key-modifier options
Keys vk // virtual-key code
);
[System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数
public static extern bool UnregisterHotKey(
IntPtr hWnd, // handle to window
int id // hot key identifier
);
private void MainForm_Activated(object sender, EventArgs e) //注册热键
{
RegisterHotKey(Handle, 100, 0, Keys.Escape); //定义热键为Escape,这里实现了屏幕系统退出
RegisterHotKey(Handle, 101,0, Keys.F1); //注册F1热键,根据id值101来判断需要执行哪个函数
RegisterHotKey(Handle, 102,0, Keys.F2); //注册F2热键,根据id值102来判断需要执行哪个函数
//注册热键的函数中,其中为0的参数表示没有组合键,假如需要设置组合键,可以声明一个枚举类型来表示,可以从网上查资料
}
////////尤其注意:Form注销热键的事件是Deactivate,不是Leave了。
private void MainForm_Deactivate(object sender, EventArgs e) // 注销热键。
{
UnregisterHotKey(Handle, 100);//卸载第1个快捷键
UnregisterHotKey(Handle, 101); //缷载第2个快捷键
UnregisterHotKey(Handle, 102); //缷载第2个快捷键
}
protected override void WndProc(ref Message m) // 重载WndProc函数
{
const int WM_HOTKEY = 0x0312;
//按快捷键
switch (m.Msg)
{
case WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case 100: //Escape 退出
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.WindowState = FormWindowState.Normal;
break;
case 101: //F1 设置
foreach (Form temp in Application.OpenForms)
{
OpendFormName.Add(temp.Name);
}
using (Seting setForm = new Seting())
{
if (!OpendFormName.Contains(setForm.Name))
{
setForm.ShowDialog();
}
}
OpendFormName.Clear();
break;
case 102: //F2 全屏
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
this.webBrowser1.Dock = DockStyle.Fill;
break;
}
break;
}
base.WndProc(ref m);
}
}