文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>线程内键盘钩子实现Winforn快捷键(组合键)

线程内键盘钩子实现Winforn快捷键(组合键)

时间:2011-06-04  来源:索马

线程内键盘钩子实现Winforn快捷键(组合键)代码全都在这里.比较简单..需要的朋友可以拷贝去用.. 发现网上的钩子例子都是使用C++的,C#线程内的钩子很少可以不出错正常运行的.. 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public class KeyboardHook
    {
        HookProc KeyboardHookProcedure; //声明键盘钩子事件类型.
        //装置钩子的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        //卸下钩子的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);
        //下一个钩挂的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
        [DllImport("Kernel32.dll")]
        public static extern int GetLastError();
        [DllImport("kernel32.dll", CharSet = CharSet.Auto,
            CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
        //取线程
        [DllImport("kernel32.dll")]
        public static extern int GetCurrentThreadId();
        static int hKeyboardHook = 0; //键盘钩子句柄
        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        public const int WH_KEYBOARD = 2;   // 键盘消息钩子(线程钩子)
        public event KeyEventHandler OnKeyDownEvent;
        public KeyboardHook()
        {
            Start();
        }
        ~KeyboardHook()
        {
            Stop();
        }
        /// <summary>
        /// 安装钩子
        /// </summary>
        public void Start()
        {
            //安装一个线程键盘钩子 
            if (hKeyboardHook == 0)
            {
                KeyboardHookProcedure = new HookProc(KeyboardHookProc);
                Process curProcess = Process.GetCurrentProcess();
                ProcessModule curModule = curProcess.MainModule;
                hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardHookProcedure,
                    IntPtr.Zero, GetCurrentThreadId());
                if (hKeyboardHook == 0)
                {
                    Stop();
                    Console.WriteLine(GetLastError());
                    throw new Exception("SetWindowsHookEx ist failed.");
                }
            }
        }
        /// <summary>
        /// 卸载钩子
        /// </summary>
        public void Stop()
        {
            bool retKeyboard = true;
            if (hKeyboardHook != 0)
            {
                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                hKeyboardHook = 0;
            }
            //如果卸下钩子失败 
            if (!(retKeyboard))
            {
                Console.WriteLine(GetLastError());
                throw new Exception("UnhookWindowsHookEx failed.");
            }
        }

        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        { 
            if (nCode >= 0)
            {
                if (lParam.ToInt32()<0)
                {//如果小于0那么是抬起
                    return 1;
                }
                Keys keyData = (Keys)wParam;
                foreach (ShortKey keyModel in ShortCenter.Instance.Keys)
                {
                    if (keyModel.Key == keyData && (int)Control.ModifierKeys == (int)keyModel.ControlKey)
                    {
                        keyModel.DoEvent();
                        return 1;
                    }
                }
            }
            return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
        }
    }

上面是一个钩子类,主要实现键盘消息拦截,而且是拦截线程内部的..

 

使用

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public partial class Form3 : Form
    {
        KeyboardHook hook;
        public Form3()
        {
            InitializeComponent();
            hook = new KeyboardHook();
        }


        private void Form3_Load(object sender, EventArgs e)
        {
            ShortKey @short = new ShortKey();
            @short.Key = Keys.S;
            @short.ControlKey = Keys.Control;
            @short.ExecuteEvent += (object o, EventArgs arg) => { MessageBox.Show( string.Format("你按下了Key:{0},Control:{1}", ((ShortKey)o).Key ,((ShortKey)o).ControlKey)); };
            ShortCenter.Instance.Keys.Add(@short);

            @short = new ShortKey();
            @short.Key = Keys.F1;
            @short.ExecuteEvent += (object o, EventArgs arg) => { MessageBox.Show(string.Format("你按下了Key:{0},Control:{1}", ((ShortKey)o).Key, ((ShortKey)o).ControlKey)); };
            ShortCenter.Instance.Keys.Add(@short);

            @short = new ShortKey();
            @short.Key = Keys.F1;
            @short.ControlKey = Keys.Alt;
            @short.ExecuteEvent += (object o, EventArgs arg) => { MessageBox.Show(string.Format("你按下了Key:{0},Control:{1}", ((ShortKey)o).Key, ((ShortKey)o).ControlKey)); };
            ShortCenter.Instance.Keys.Add(@short);

        }
    }
    public class ShortCenter
    {
        public ShortCenter()
        {
            _keys = new List<ShortKey>();
        }
        private static ShortCenter _instance = new ShortCenter();
        public static ShortCenter Instance
        {
            get { return _instance; }
        }
        private List<ShortKey> _keys;
        public List<ShortKey> Keys
        {
            get { return _keys; }
            set { _keys = value; }
        }
    }

    public class ShortKey
    {
        public ShortKey()
        {

        }
        private Keys _key;
        private Keys _controlKey = Keys.None;

        /// <summary>
        /// 按下的普通键
        /// </summary>
        public Keys Key
        {
            get { return _key; }
            set
            {
                _key = value;
            }
        }
        /// <summary>
        /// 控制键
        /// </summary>
        public Keys ControlKey
        {
            get { return _controlKey; }
            set
            {
                _controlKey = value;
            }
        }
        /// <summary>
        /// 按下快捷键以后执行的操作
        /// </summary>
        public event EventHandler ExecuteEvent;
        /// <summary>
        /// 执行事件
        /// </summary>
        public void DoEvent()
        {
            if (ExecuteEvent != null)
                ExecuteEvent(this,new EventArgs());
        }
    }

}

 

 

 

 

相关阅读 更多 +
排行榜 更多 +
边境检察最后区域手机版下载

边境检察最后区域手机版下载

角色扮演 下载
酋长你别跑手游下载

酋长你别跑手游下载

休闲益智 下载
心动漫画app下载官方版

心动漫画app下载官方版

浏览阅读 下载