asmrobot
2019-11-21 589ed88a5924a7494e21b95b6bbff5e46ff49ddd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
 
namespace RichCreator.Utility
{
    /// <summary>
    /// 鼠标全局钩子
    /// </summary>
    public class MouseHook:IDisposable
    {
 
        public MouseHook(MouseEvent mouseEvent)
        {
            this.OnMouseActivity = mouseEvent;
        }
 
        public enum MouseButton:Int32
        {
            None                =0,
            MouseMove           = 0x200,
            LeftButtonDown      = 0x201,
            RightButtonDown     = 0x204,
            middleButtonDown   = 0x207,
            LeftButtonUp        = 0x202,
            RightButtonUp       = 0x205,
            MiddleButtonUp     = 0x208,
            LeftButtonClick = 0x203,
            RightButtonClick = 0x206,
            MiddleButtonClick = 0x209,
        }
 
        /// <summary>
        /// 鼠标事件
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="clickCount"></param>
        /// <param name="button"></param>
        public delegate void MouseEvent(Int32 x,Int32 y,Int32 clickCount,MouseButton button);
        
 
        /// <summary>
        /// 点
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        private class POINT
        {
            public int x;
            public int y;
        }
 
        /// <summary>
        /// 钩子结构体
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        private class MouseHookStruct
        {
            public POINT pt;
            public int hWnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }
 
 
        // 钩子回调函数
        private delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
 
 
        private const int WH_MOUSE_LL = 14; // mouse hook constant
        // 装置钩子的函数
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
 
        // 卸下钩子的函数
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern bool UnhookWindowsHookEx(int idHook);
 
        // 下一个钩挂的函数
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
 
        private event MouseEvent OnMouseActivity;  // 全局的鼠标事件
        private HookProc mouseHookProcedure;// 声明鼠标钩子事件类型
        private static int hMouseHook = 0; // 鼠标钩子句柄
        private bool isFinalize=false;//是否已主动释放
        
 
        /// <summary>
        /// 启动全局钩子
        /// </summary>
        public void Start()
        {
            // 安装鼠标钩子
            if (hMouseHook == 0)
            {
                mouseHookProcedure = new HookProc(MouseHookProc);
                Module module = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0];
                // 生成一个HookProc的实例.
                hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseHookProcedure, Marshal.GetHINSTANCE(module), 0);
 
                //假设装置失败停止钩子
                if (hMouseHook == 0)
                {
                    Close();
                    throw new Exception("SetWindowsHookEx failed.");
                }
            }
        }
 
 
        
        /// <summary>
        /// 停止全局钩子
        /// </summary>
        public void Close()
        {
            if (isFinalize)
            {
                return;
            }
            bool retMouse = true;
 
            if (hMouseHook != 0)
            {
                retMouse = UnhookWindowsHookEx(hMouseHook);
                hMouseHook = 0;
            }
 
            // 假设卸下钩子失败
            if (!(retMouse))
            {
                throw new Exception("UnhookWindowsHookEx failed.");
            }
            isFinalize = true;
            GC.SuppressFinalize(this);
        }
 
        /// <summary>
        /// 鼠标钩子回调函数
        /// </summary>
        private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            // 假设正常执行而且用户要监听鼠标的消息
            if ((nCode >= 0) && (OnMouseActivity != null))
            {
                MouseButton button = MouseButton.None;
                Enum.TryParse<MouseButton>(wParam.ToString(), out button);
 
                int clickCount = 0;
                switch (button)
                {
                    case MouseButton.LeftButtonDown:
                        clickCount = 1;
                        break;
                    case MouseButton.LeftButtonUp:
                        clickCount = 1;
                        break;
                    case MouseButton.LeftButtonClick:
                        clickCount = 2;
                        break;
                    case MouseButton.RightButtonDown:
                        clickCount = 1;
                        break;
                    case MouseButton.RightButtonUp:
                        clickCount = 1;
                        break;
                    case MouseButton.RightButtonClick:
                        clickCount = 2;
                        break;
                }
 
                // 从回调函数中得到鼠标的信息
                MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
                
                //MouseEvent e = new MouseEventArgs(button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, 0);
 
                //// 假设想要限制鼠标在屏幕中的移动区域能够在此处设置
                //// 后期须要考虑实际的x、y的容差
                //if (!Screen.PrimaryScreen.Bounds.Contains(e.X, e.Y))
                //{
                //    //return 1;
                //}
 
                OnMouseActivity(MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y,clickCount, button);
            }
 
            // 启动下一次钩子
            return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
        }
 
        public void Dispose()
        {
            Close();
        }
    }
}