添加一个HotKey类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyHotKey
{
public class HotKey
{
//使用DllImport调用Windows API函数
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd, //要定义热键的窗口的句柄
int id, //定义热键id
KeyModifiers fsModifiers, //标识热键组合键
Keys vk //定义热键键值
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd, //要取消热键的窗口的句柄
int id //要取消热键的id
);
//定义组合键枚举,使用别名代替数字
[Flags()] //枚举位域的用法,各枚举值可组合。
public enum KeyModifiers
{
None=0,
Alt=1,
Ctrl=2,
Shift=4,
WindowsKey=8
}
}
}
在窗体事件中注册或注销热键,并重载消息处理函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyHotKey
{
public class HotKey
{
//使用DllImport调用Windows API函数
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd, //要定义热键的窗口的句柄
int id, //定义热键id
KeyModifiers fsModifiers, //标识热键组合键
Keys vk //定义热键键值
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd, //要取消热键的窗口的句柄
int id //要取消热键的id
);
//定义组合键枚举,使用别名代替数字
[Flags()] //枚举位域的用法,各枚举值可组合。
public enum KeyModifiers
{
None=0,
Alt=1,
Ctrl=2,
Shift=4,
WindowsKey=8
}
}
}