注冊系統熱鍵類(原創)
C#注冊系統熱鍵類,參考多篇文章封裝而成,只需一個構造函數即可完成,尤其適合于WPF
參考文章:http://www.rzrgm.cn/dabaopku/archive/2010/02/21/1670793.html
系統熱鍵類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using System.Collections;
namespace ThunderStarter
{
/// <summary>
/// 直接構造類實例即可注冊
/// 自動完成注銷
/// 注意注冊時會拋出異常
/// </summary>
class HotKey
//注冊系統熱鍵類
//熱鍵會隨著程序結束自動解除,不會寫入注冊表
{
#region Member
int KeyId ; //熱鍵編號
IntPtr Handle ; //窗體句柄
Window window ; //熱鍵所在窗體
uint Controlkey ; //熱鍵控制鍵
uint Key ; //熱鍵主鍵
public delegate void OnHotkeyEventHandeler(); //熱鍵事件委托
public event OnHotkeyEventHandeler OnHotKey=null; //熱鍵事件
static Hashtable KeyPair = new Hashtable(); //熱鍵哈希表
private const int WM_HOTKEY = 0x0312; // 熱鍵消息編號
public enum KeyFlags //控制鍵編碼
{
MOD_ALT = 0x1,
MOD_CONTROL = 0x2,
MOD_SHIFT = 0x4,
MOD_WIN = 0x8
}
#endregion
/// <summary>
/// 構造函數
/// </summary>
/// <param name="win">注冊窗體</param>
/// <param name="control">控制鍵</param>
/// <param name="key">主鍵</param>
public HotKey(Window win, HotKey.KeyFlags control, Keys key)
//構造函數,注冊熱鍵
{
Handle = new WindowInteropHelper(win).Handle;
window=win;
Controlkey = (uint)control;
Key = (uint)key;
KeyId=(int)Controlkey+(int)Key*10;
if (HotKey.KeyPair.ContainsKey(KeyId))
{
throw new Exception("熱鍵已經被注冊!");
}
//注冊熱鍵
if(false == HotKey.RegisterHotKey(Handle, KeyId, Controlkey, Key))
{
throw new Exception("熱鍵注冊失敗!");
}
if(HotKey.KeyPair.Count==0){
//消息掛鉤只能連接一次!!
if(false == InstallHotKeyHook(this))
{
throw new Exception("消息掛鉤連接失敗!");
}
}
//添加這個熱鍵索引
HotKey.KeyPair.Add(KeyId, this);
}
#region core
[System.Runtime.InteropServices.DllImport("user32")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint controlKey, uint virtualKey);
[System.Runtime.InteropServices.DllImport("user32")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
static private bool InstallHotKeyHook(HotKey hk)
//安裝熱鍵處理掛鉤
{
if (hk.window == null || hk.Handle==IntPtr.Zero)
return false;
//獲得消息源
System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(hk.Handle);
if (source==null) return false;
//掛接事件
source.AddHook(HotKey.HotKeyHook);
return true;
}
static private IntPtr HotKeyHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
//熱鍵處理過程
{
if (msg == WM_HOTKEY)
{
HotKey hk = (HotKey)HotKey.KeyPair[(int)wParam];
if (hk.OnHotKey != null) hk.OnHotKey();
}
return IntPtr.Zero;
}
~HotKey()
//析構函數,解除熱鍵
{
HotKey.UnregisterHotKey(Handle, KeyId);
}
#endregion
}
}

浙公網安備 33010602011771號