开发环境:VS2005, C#语言
为了给一个程序加一个系统级的热键,在开发时需要使用到下面的代码,就是在程序中注册和卸载热键。
1。首先在Form1类的函数中添加如下代码:
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
注意,使用上面的代码前,必须使用"using System.Runtime.InteropServices;"来引入命名空间。
2。在Form1的构造函数中注册热键:
public Form1()
{
RegisterHotKey(Handle, 100, 0, Keys.Escape); //注册热键: Esc
}
3. 重写窗口的WndProc函数:
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x312)
{
if (m.WParam.ToInt32() == 100)
this.Close(); //当按下Esc键时关闭本窗口
}
base.WndProc(ref m);
}
4。在析构函数中卸载热键:
~Form1()
{
UnregisterHotKey(Handle, 100); //窗口未激活时卸载热键
}
这样就完成了我们的所有设置。但是这个添加的热键是系统级热键,也就是说不管这个窗口有没有被激活,这个热键都是能起作用的。
但是有时我们并不希望这种热键是系统级的,而是希望当前窗口被激活时,该热键才起作用,如果没有被激活,该热键不起作用。于是,我想了办法,就是更改热键注册和卸载的时间。
思路:在Form1的Form1_Activated事件中注册热键,在Form1_Deactivate中卸载热键,其他不变,代码如下:
private void Form1_Activated(object sender, EventArgs e)
{
RegisterHotKey(Handle, 100, 0, Keys.Escape); //在窗口激活时注册热键: Esc
}
private void Form1_Deactivate(object sender, EventArgs e)
{
UnregisterHotKey(Handle, 100); //窗口未激活时卸载热键
}
这样就达到了窗口级的热键。
根据同样的思路,你可以选择其他的时机来注册或卸载热键!