C#实现全局热键响应,失去焦点情况下响应全局快捷键
1 、引入API注册和注销热键的函数,建立一个类文件,命名为 HotKey.cs ,代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices; //使用DllImport
using System.Windows.Forms; //使用keys
{
class HotKey
{
[DllImport("user32.dll")]
// 用于注册热键
public static extern bool RegisterHotKey(
IntPtr hWnd, // 要定义热键的窗口的句柄
int id, // 定义热键 ID (不能与其它 ID 重复)
KeyModifiers fsModifiers, // 标识热键是否在按 Alt 、 Ctrl 、 Shift 、 Windows 等键时才会生效
Keys vk // 定义热键的内容
);
[DllImport("user32.dll")]
// 注销热键
public static extern bool UnregisterHotKey(
IntPtr hWnd, // 要取消热键的窗口的句柄
int id // 要取消热键的 ID
);
// 定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Ctrl = 2,
Shift = 4,
WindowsKey = 8
}
}
}
public static extern bool RegisterHotKey() 这个函数用于注册热键 ,public static extern bool UnregisterHotKey() 这个函数用于注销热键。由于这个函数需要引用 user32.dll 动态链接库后才能使用,并且user32.dll 是 非托管代码,不能用命名空间的方式直接引用,所以需要用“DllImport”进行引入后才能使用。
2. 在程序中设置热键
//设置热键
private void textBoxHotKey_Leave(object sender, EventArgs e)
{
if (textBoxHotKey.Text == "")
return;
hidetask.m_HotKey = (Keys)Enum.Parse(typeof(Keys), textBoxHotKey.Text.ToUpper());
//删除原热键的注册,重新注册热键
HotKey.UnregisterHotKey(Handle, 0xAAAA);
HotKey.RegisterHotKey(Handle, 0xAAAA, HotKey.KeyModifiers.Ctrl, hidetask.m_HotKey);
}
3. //监视 Windows 消息 ,重载WndProc方法,用于实现热键响应
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312; //如果m.Msg的值为0x0312那么表示用户按下了热键
switch (m.Msg)
{
case WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case 0xAAAA:
OnHideTaskHotKey();
break;
}
break;
}
base.WndProc(ref m);
}
4. 响应热键处理程序:
//热键响应函数
private bool OnHideTaskHotKey()
{
//.....................
return true;
}
5. string 转换为Keys的方法
string m_HotKey
m_HotKey = (Keys)Enum.Parse(typeof(Keys), textBoxHotKey.Text.ToUpper());