c#在操作winApi时有很多不便。比如没有指针就很让人头痛。
这两天需要写一个注册全局热键的程序,于是写了这个类。注册热键更轻松了
调用非常简单:
hk = new HotKey();
hk.RegHotKey(Keys.End,fun);//第2个参数是方法名称
hk.UnRegHotKey(Keys.End);//注销热键
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace xinjeHotkey
{
public class HotKey:Form
{
private List<idAndFun> keyIds = new List<idAndFun>();
private uint id = 0;
[DllImport("user32.dll")]
public static extern UInt32 RegisterHotKey(IntPtr hWnd, UInt32 id, UInt32 fsModifiers, UInt32 vk);
[DllImport("user32.dll")]
public static extern UInt32 UnregisterHotKey(IntPtr hWnd, UInt32 id);
public HotKey()
{
}
public delegate void myfun();
public void RegHotKey(Keys key,myfun e)
{
id++;
idAndFun fi = new idAndFun();
fi.id = id;
fi.key = (uint)key;
fi.mf = (object)e;
keyIds.Add(fi);
RegisterHotKey(this.Handle, id, 0, (uint)key);
}
public void UnRegHotKey(Keys key)
{
uint temp = (uint)key;
for (int i = 0; i < keyIds.Count; i++)
{
if (keyIds[i].key == temp)
{
UnregisterHotKey(this.Handle, keyIds[i].id);
keyIds.RemoveAt(i);
}
}
}
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY)
{
for (int i = 0; i < keyIds.Count; i++)
{
if (m.WParam.ToInt32() == keyIds[i].id)
{
myfun mff = (myfun)keyIds[i].mf;
mff();
}
}
}
base.WndProc(ref m);
}
}
class idAndFun
{
public uint id;
public uint key;
public object mf;
}
}