轉自:http://blog.csdn.net/xiahn1a/article/details/42561015
這里需要引用到“user32.dll”。對於Win32的API,調用起來還是需要dllimport的。
我們聲明一個Hotkey類,導入相應的方法。
class HotKey { //調用WIN32的API [DllImport("user32.dll", SetLastError = true)] //聲明注冊快捷鍵方法,方法實體dll中。參數為窗口句柄,快捷鍵自定義ID,Ctrl,Shift等功能鍵,其他按鍵。 public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk); [DllImport("user32.dll", SetLastError = true)] //注銷快捷鍵方法的聲明。 public static extern bool UnregisterHotKey(IntPtr hWnd, int id); }
在程序開始,Windows_Loaded方法中就要對快捷鍵進行注冊。
方法是首先獲取窗口句柄。可能C#的程序員對於句柄這個概念比較陌生,因為語言的高度封裝。但是因為我們調用的是Win32的方法,還是要自己一步一步去做的。
然后再注冊表中注冊一個鍵值,添加hook監聽窗口事件。通過重寫winproc,相應鍵盤快捷鍵。
這一部分都是Win32程序設計的內容。
/// <summary> /// 窗體建立完成時調用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Window_Loaded(object sender, RoutedEventArgs e) { Handle = new WindowInteropHelper(this).Handle; //獲取窗口句柄 RunHotKey(); //注冊並監聽HotKey } /// <summary> /// 添加快捷鍵監聽 /// </summary> private void RunHotKey() { RegisterHotKey(); //注冊截圖快捷鍵 HwndSource source = HwndSource.FromHwnd(Handle); if (source != null) source.AddHook(WndProc); //添加Hook,監聽窗口事件 } /// <summary> /// 注冊快捷鍵 /// </summary> private void RegisterHotKey() { //101為快捷鍵自定義ID,0x0002為Ctrl鍵, 0x0001為Alt鍵,或運算符|表同時按住兩個鍵有效,0x41為A鍵。 bool isRegistered = HotKey.RegisterHotKey(Handle, 101, (0x0002 | 0x0001), 0x41); if (isRegistered == false) { System.Windows.MessageBox.Show("截圖快捷鍵Ctrl+Alt+A被占用", "警告", MessageBoxButton.OK, MessageBoxImage.Warning); } } /// <summary> /// 重寫WndProc函數,類型為虛保護,響應窗體消息事件 /// </summary> /// <param name="hwnd"></param> /// <param name="msg">消息內容</param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <param name="handled">是否相應完成</param> /// <returns></returns> protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { //0x0312表示事件消息為按下快捷鍵 case 0x0312: CatchScreen(); break; } return IntPtr.Zero; }