日期:2014-05-18 浏览次数:20940 次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace 编辑器
{
public class HotKey: Form1
{
//委托 key 函数
public delegate void delegateKeyPress(object sender, EventArgsKey e);
// 自增ID 标示
private int idForDiff = 0;
public IntPtr hWnd{get;set;} //当前空中句柄
public Control control { get; set; }
//要注册的按键:
public List<keyNode> keys { get; set; }
/// <summary>
/// 如果函数执行成功,返回值不为0。
/// 如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。
///
/// </summary>
/// <param name="hWnd"></param>
/// <param name="id"></param>
/// <param name="fsModifiers"></param>
/// <param name="vk"></param>
/// <returns></returns>
[DllImport("user32.dll ", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd, //要定义热键的窗口的句柄
int id, //定义热键ID(不能与其它ID重复)
KeyModifiers fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
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
}
//构造函数
public HotKey(IntPtr hwnd)
{
this.control = null;
this.hWnd = hwnd;
this.keys = new List<keyNode>();//对象init
}
//构造函数
public HotKey(Control control)
{
this.control = control;
this.hWnd = control.Handle;
this.keys = new List<keyNode>();//对象init
}
//注册按键:
public void AddKeyToRegister(IEnumerable<keyNode> keys)
{
foreach (keyNode key in keys)
{
keyNode k = new keyNode(key.key,key.keyMode,key.keyPassFunction);
HotKey.RegisterHotKey(this.hWnd, this.idForDiff, k.keyMode, k.key);
k.keyPassFunction = key.keyPassFunction;
k.id = this.idForDiff;
this.idForDiff++;
this.keys.Add(k);
}
}
public void AddKeyToRegister(Keys key,HotKey.KeyModifiers keyMode, delegateKeyPress keyFunction)
{
keyNode k = new keyNode(key, keyMode, keyFunction);
HotKey.RegisterHotKey(this.hWnd, this.idForDiff, k.keyMode, k.key);
k.id = this.idForDiff;
this.idForDiff++;
this.keys.Add(k);
}
}
//每一个Key对象
public class keyNode
{
public Keys key { get; set; }
public 编辑器.HotKey.KeyModifiers keyMode { get; set; }
public int id { get; set; }
public 编辑器.HotKey.delegateKeyPress keyPassFunction { get; set; }
public keyNode(Keys key, 编辑器.HotKey.KeyModifiers keyModefier,编辑器.HotKey.delegateKeyPress keyPassFunction )
{
this.key = key;
this.keyMode = keyModefier;
this.keyPassFunction = keyPassFunction;
}
}
public class EventArgsKey : EventArgs
{