鼠标 hook 源码 C#版

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

namespace MouseHook20200119
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region  所需

        public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
        //整数14表示全局钩子类型,其他类型对应的数字可以从MicrosoftSDK中的Winuser.h头文件中查看
        public const int WH_MOUSE = 14;
        [DllImport("user32.dll")]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        [DllImport("user32.dll")]
        public static extern bool UnhookWindowsHookEx(int idHook);
        [DllImport("user32.dll")]
        public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
        #endregion

        static int hHook = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        StringBuilder sb = new StringBuilder();
        public int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            switch ((int)wParam)
            {
                case 513: //0x201
                          //sb.AppendLine("鼠标左键按下");

                    break;
                case 516://0x204
                    //sb.AppendLine("鼠标右键");
                    break;
                case 519:
                    //sb.AppendLine("鼠标中键");
                    break;
                case 514://0x202
                         //sb.AppendLine("鼠标左键松开");

                    break;
                case 517:
                    //sb.AppendLine("鼠标右键");
                    break;
                case 520:
                    //sb.AppendLine("鼠标中键");
                    break;
            }
            //var t = sb.ToString();
            //if (nCode < 0)
            //{
            //    return 1;
            //    //返回真;即截断消息传递,
            //    //否则不截断
            //    //return CallNextHookEx(hHook, nCode, wParam, lParam);
            //}
            //else
            //{
            //    return 1;
            //}
            return CallNextHookEx(hHook, nCode, wParam, lParam);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (hHook == 0) //句柄未初始化
            {
                hHook = SetWindowsHookEx(WH_MOUSE,
                   MouseHookProc,
                   IntPtr.Zero,
                   0
                    );
            }
            if (hHook > 0)
            {
                MessageBox.Show("安装钩子成功!");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            UnhookWindowsHookEx(hHook);
            MessageBox.Show(hHook.ToString());

        }
    }
}
posted @ 2020-01-19 20:53  enych  阅读(461)  评论(0编辑  收藏  举报