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 ListkeyIds = new List (); 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; } }