最近,在写项目时需要用到快捷键,看了一些想干资料收获很多,现在将它封装成一个类以便日后用着方便!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; //调用非托管程序集
using System.Windows.Forms; //能调用Keys的枚举集合
namespace 快捷键
{
class RegisterHotKeyClass
{
public enum ModifiersKey //组合键的枚举
{
None = 0,
Alt = 1,
crtl = 2,
Shift = 4,
Windows = 8
}
public const int WM_HOTKEY =0x0312; //热键的消息号
[DllImportAttribute("user32.dll", EntryPoint = "RegisterHotKey")]
private static extern bool registerHotKey
(
IntPtr hWnd, //接受热键的窗口句柄(句柄:窗体的系统代号)
int id, //热键编号
int fsModifiers, //是否为组合键 例如ctrl shift 等等
int vk //一般按键 a,c 等等
);
[DllImportAttribute("user32.dll", EntryPoint = "UnregisterHotKey")]
private static extern bool unregisterHotKey
(
IntPtr hWnd, //接受热键的窗口句柄(句柄:窗体的系统代号)
int id //热键编号上面注册热键的编号
);
/// <summary>
/// 设置快捷键
/// </summary>
/// <param name="handle">要注册的窗体的句柄</param>
/// <param name="id">热键的Id</param>
/// <param name="mK">所需的组合键的代码</param>
/// <param name="keyCode">按键的代码</param>
public static void RegisterHotKey(IntPtr handle,int id,ModifiersKey mK,Keys keyCode)
{
registerHotKey(handle, id, Convert.ToInt32(mK), Convert.ToInt32( keyCode));
}
/// <summary>
/// 注销快捷键
/// </summary>
/// <param name="handle">已注册的快捷键的句柄</param>
/// <param name="id">要注销的快捷键id</param>
public static void UnregisterHotKey(IntPtr handle, int id)
{
unregisterHotKey(handle, id);
}
}
}
调用例子:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 快捷键
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RegisterHotKeyClass.RegisterHotKey(this.Handle, 1000, RegisterHotKeyClass.ModifiersKey.Shift, Keys.A);
RegisterHotKeyClass.RegisterHotKey(this.Handle, 1001, RegisterHotKeyClass.ModifiersKey.None, Keys.P);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
RegisterHotKeyClass.UnregisterHotKey(this.Handle, 1000);
RegisterHotKeyClass.UnregisterHotKey(this.Handle, 1001);
}
protected override void WndProc(ref Message m) //监控消息泵 ,所有进入这个程序的消息源头
{
switch (m.Msg)
{
case RegisterHotKeyClass.WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case 1000:
MessageBox.Show("shift+A");
break;
case 1001:
MessageBox.Show("P");
break;
}
break;
default:
base.WndProc(ref m);
break;
}
}
}
}