VS2010开发如何在c#中使用Ctrl、Alt、Tab等全局组合快捷键
生活随笔
收集整理的這篇文章主要介紹了
VS2010开发如何在c#中使用Ctrl、Alt、Tab等全局组合快捷键
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1、新建一個類?HotkeyHelper?
using System; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Collections;namespace 黃聰 {public delegate void HotkeyEventHandler(int hotKeyID);public class HotkeyHelper : IMessageFilter{public event HotkeyEventHandler OnHotkey;public enum KeyFlags{MOD_ALT = 0x1,MOD_CONTROL = 0x2,MOD_SHIFT = 0x4,MOD_WIN = 0x8}class NativeMethods{private NativeMethods() { }#region WIN32 API[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);[DllImport("kernel32.dll")]public static extern UInt32 GlobalAddAtom(String lpString);[DllImport("kernel32.dll")]public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom);#endregion}Hashtable keyIDs = new Hashtable();IntPtr hWnd;public HotkeyHelper(IntPtr hWnd){this.hWnd = hWnd;Application.AddMessageFilter(this);}public int RegisterHotkey(Keys Key, KeyFlags keyflags){UInt32 hotkeyid = NativeMethods.GlobalAddAtom(System.Guid.NewGuid().ToString());NativeMethods.RegisterHotKey((IntPtr)hWnd, hotkeyid, (UInt32)keyflags, (UInt32)Key);keyIDs.Add(hotkeyid, hotkeyid);return (int)hotkeyid;}public void UnregisterHotkeys(){Application.RemoveMessageFilter(this);foreach (UInt32 key in keyIDs.Values){NativeMethods.UnregisterHotKey(hWnd, key);NativeMethods.GlobalDeleteAtom(key);}}public bool PreFilterMessage(ref Message m){if (m.Msg == 0x312){if (OnHotkey != null){foreach (UInt32 key in keyIDs.Values){if ((UInt32)m.WParam == key){OnHotkey((int)m.WParam);return true;}}}}return false;}} }?
2、在窗口創(chuàng)建(FrmMain_Load)的時候注冊快捷鍵
private void FrmMain_Load(object sender, EventArgs e) {hotkeyHelper = new HotkeyHelper(this.Handle);int favKey = hotkeyHelper.RegisterHotkey(Keys.F, HotkeyHelper.KeyFlags.MOD_CONTROL); //注冊Ctrl+Fint nextKey = hotkeyHelper.RegisterHotkey(Keys.G, HotkeyHelper.KeyFlags.MOD_CONTROL);//注冊Ctrl+GhotkeyHelper.OnHotkey += new HotkeyEventHandler(OnHotkey); }?
3、熱鍵的響應(yīng)方法
private void OnHotkey(int hotkeyID) {if (hotkeyID == favKey){//do something }else if (hotkeyID == nextKey){//do something else } }?
4、當(dāng)然在窗體關(guān)閉的時候,一定要注銷掉快捷鍵
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) {hotkeyHelper.UnregisterHotkeys(); }?
本文轉(zhuǎn)自黃聰博客園博客,原文鏈接:http://www.cnblogs.com/huangcong/p/4047346.html,如需轉(zhuǎn)載請自行聯(lián)系原作者
總結(jié)
以上是生活随笔為你收集整理的VS2010开发如何在c#中使用Ctrl、Alt、Tab等全局组合快捷键的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 千万条据下的分页
- 下一篇: util-C# 复杂条件查询(sql 复