Posts C# - Global Mouse Hook
Post
Cancel

C# - Global Mouse Hook

Source Code


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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;

namespace Rito
{
    /*
         [기능]
             - 마우스 누름, 뗌, 휠 올림/내림, 휠클릭 이벤트 글로벌 후킹

         [메소드]
            - 후킹 시작 : Begin()
            - 후킹 종료 : Stop()
            - 핸들러 추가 : Mouse~, Middle~, Left~, Right~ 이벤트 핸들러에 메소드 등록
            - 마우스 현재 위치 받아오기 : GetCursorPosition()
            - 마우스 이벤트 발생시키기  : Force~()
    */
    /*
        [2022. 04. 14. 기능 추가]
            - BlockMouseClick() : 마우스가 현재 위치한 창에 대해 클릭 차단
            - AllowMouseClickAll() : 마우스 클릭 차단된 적 있는 모든 창에 대해 클릭 허용
            - ToggleShowCursor(bool) : 마우스 커서 보이기/숨기기
     */
    class GlobalMouseHook
    {
        /***********************************************************************
        *                               DLL Imports
        ***********************************************************************/
        #region .
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, MouseHookProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        // 강제로 마우스 이벤트 발생
        [DllImport("user32.dll")] // 입력 제어
        static extern void mouse_event(uint dwFlags, uint dx, uint dy, int dwData, int dwExtraInfo);

        [DllImport("user32.dll")] // 커서 위치 제어
        static extern int SetCursorPos(int x, int y);

        [DllImport("user32")]
        public static extern int GetCursorPos(out MousePoint pt);



        [DllImport("user32.dll")]
        static extern bool EnableWindow(IntPtr hWnd, bool enable);
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")]
        private static extern int ShowCursor(bool enable);

        #endregion
        /***********************************************************************
        *                               Definitions
        ***********************************************************************/
        #region .
        [StructLayout(LayoutKind.Sequential)]
        public struct Point
        {
            public int x;
            public int y;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MouseHookInfo
        {
            public Point pt;
            public uint mouseData;
            public uint flags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        /// <summary> 마우스 이벤트 값 - 읽기용 </summary>
        private enum MouseEvent
        {
            MouseMove = 0x0200,

            LButtonDown = 0x0201,
            LButtonUp = 0x0202,
            //LButtonDoubleClick = 0x0203,

            RButtonDown = 0x0204,
            RButtonUp = 0x0205,
            //RButtonDoubleClick = 0x0206,

            MButtonDown = 0x0207,
            MButtonUp = 0x0208,

            MouseWheel = 0x020A,
        }

        /// <summary> 커서 좌표 </summary>
        public struct MousePoint
        {
            public int x;
            public int y;
        }

        #endregion
        /***********************************************************************
        *                               Const Variables
        ***********************************************************************/
        #region .
        // 마우스 입력용
        private const uint LB_DOWN = 0x00000002; // 왼쪽 마우스 버튼 누름
        private const uint LB_UP = 0x00000004; // 왼쪽 마우스 버튼 뗌

        private const uint RB_DOWN = 0x00000008;  // 오른쪽 마우스 버튼 누름
        private const uint RB_UP = 0x000000010; // 오른쪽 마우스 버튼 뗌

        private const uint MB_DOWN = 0x00000020;  // 휠 버튼 누름
        private const uint MB_UP = 0x000000040; // 휠 버튼 뗌
        private const uint WHEEL = 0x00000800;  // 휠 스크롤

        private const int WH_MOUSE_LL = 14;

        const int TRUE = 1;
        const int FALSE = 0;
        #endregion
        /***********************************************************************
        *                               Privates
        ***********************************************************************/
        #region .
        private delegate IntPtr MouseHookProc(int code, IntPtr wParam, IntPtr lParam);

        private MouseHookProc mouseHookProc;

        private IntPtr hookID = IntPtr.Zero;
        private int _isHooking = FALSE;

        ~GlobalMouseHook()
        {
            Stop();
        }

        private IntPtr SetHook(MouseHookProc proc)
        {
            using (ProcessModule module = Process.GetCurrentProcess().MainModule)
                return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(module.ModuleName), 0);
        }

        private IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam)
        {
            if (code >= 0)
            {
                MouseEvent mEvent = (MouseEvent)wParam;

                switch (mEvent)
                {
                    case MouseEvent.LButtonDown:
                        OnLeftButtonDown?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;

                    case MouseEvent.LButtonUp:
                        OnLeftButtonUp?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;

                    //case MouseEvent.LButtonDoubleClick:
                    //    LeftDoubleClick?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                    //    break;

                    case MouseEvent.RButtonDown:
                        OnRightButtonDown?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;

                    case MouseEvent.RButtonUp:
                        OnRightButtonUp?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;

                    //case MouseEvent.RButtonDoubleClick:
                    //    RightDoubleClick?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                    //    break;

                    case MouseEvent.MouseMove:
                        OnMouseMove?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;

                    case MouseEvent.MButtonDown:
                        OnMiddleButtonDown?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;

                    case MouseEvent.MButtonUp:
                        OnMiddleButtonUp?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;

                    case MouseEvent.MouseWheel:
                        OnMouseWheel?.Invoke((MouseHookInfo)Marshal.PtrToStructure(lParam, typeof(MouseHookInfo)));
                        break;
                }
            }
            return CallNextHookEx(hookID, code, wParam, lParam);
        }

        #endregion
        /***********************************************************************
        *                               Event Fields
        ***********************************************************************/
        #region .
        public delegate void MouseEventHandler(MouseHookInfo mouseStruct);

        public event MouseEventHandler OnMouseMove;
        public event MouseEventHandler OnMouseWheel;

        public event MouseEventHandler OnLeftButtonDown;
        public event MouseEventHandler OnLeftButtonUp;

        public event MouseEventHandler OnRightButtonDown;
        public event MouseEventHandler OnRightButtonUp;

        public event MouseEventHandler OnMiddleButtonDown;
        public event MouseEventHandler OnMiddleButtonUp;

        #endregion
        /***********************************************************************
        *                               Additionals
        ***********************************************************************/
        #region .

        private HashSet<IntPtr> blockedWindowSet = new HashSet<IntPtr>(); // 마우스 클릭 차단된 적 있는 윈도우들


        /// <summary> 지정 윈도우에 대해 마우스 클릭 허용 </summary>
        private void AllowMouseClick(IntPtr window)
        {
            EnableWindow(window, true);
        }
        #endregion
        /***********************************************************************
        *                               Begin & Stop
        ***********************************************************************/
        #region .

        /// <summary> 마우스 후킹 시작 </summary>
        public void Begin()
        {
            // CAS
            if (System.Threading.Interlocked.CompareExchange(ref _isHooking, TRUE, FALSE) == TRUE)
                return;

            mouseHookProc = HookProc;
            hookID = SetHook(mouseHookProc);
        }

        /// <summary> 마우스 후킹 종료 </summary>
        public void Stop()
        {
            // CAS
            if (System.Threading.Interlocked.CompareExchange(ref _isHooking, FALSE, TRUE) == FALSE)
                return;

            UnhookWindowsHookEx(hookID);
            hookID = IntPtr.Zero;

            // 블락된 모든 창에 대해 마우스 클릭 허용
            AllowMouseClickAll();
        }

        #endregion
        /***********************************************************************
        *                               Public Methods
        ***********************************************************************/
        #region .

        /// <summary> 마우스가 현재 위치한 창에 대해 클릭 차단 </summary>
        public void BlockMouseClick(bool block)
        {
            IntPtr window = GetForegroundWindow();

            // EnableWindow(_, false) => 차단
            EnableWindow(GetForegroundWindow(), !block);

            // 차단 기록
            if (block)
            {
                blockedWindowSet.Add(window);
            }
        }

        /// <summary> 마우스 클릭 차단된 적 있는 모든 윈도우에 대해 클릭 허용 </summary>
        public void AllowMouseClickAll()
        {
            foreach (var w in blockedWindowSet)
            {
                AllowMouseClick(w);
            }
            blockedWindowSet.Clear();
        }

        /// <summary> 커서 보이기/숨기기 </summary>
        public void ToggleShowCursor(bool show)
        {
            ShowCursor(show);
        }

        #endregion
        /***********************************************************************
        *                               Force Event Methods
        ***********************************************************************/
        #region .
        /// <summary> x,y 위치에 커서 이동 </summary>
        public void ForceSetCursor(int x, int y)
        {
            SetCursorPos(x, y);
        }

        /// <summary> 현재 위치로부터 (xMove, yMove)만큼 커서 이동 </summary>
        public void ForceMoveCursorLocal(int xMove, int yMove)
        {
            var pos = GetCursorPosition();

            SetCursorPos(pos.x + xMove, pos.y + yMove);
        }

        // 작동 안함. 개선 필요
        /// <summary> (xBegin, yBegin) 좌표에서 (xEnd, yEnd) 좌표까지 좌클릭 드래그 </summary>
        public void ForceMouseDrag(int xBegin, int yBegin, int xEnd, int yEnd)
        {
            SetCursorPos(xBegin, yBegin);
            mouse_event(LB_DOWN, 0, 0, 0, 0);

            SetCursorPos(xEnd, yEnd);
            mouse_event(LB_UP, 0, 0, 0, 0);
        }

        /// <summary> 마우스 현재 위치 받아오기 </summary>
        public MousePoint GetCursorPosition()
        {
            GetCursorPos(out var point);
            return point;
        }

        /// <summary> 좌클릭 발생시키기 </summary>
        public void ForceLeftClick()
        {
            mouse_event(LB_DOWN, 0, 0, 0, 0);
            mouse_event(LB_UP, 0, 0, 0, 0);
        }

        /// <summary> 우클릭 발생시키기 </summary>
        public void ForceRightClick()
        {
            mouse_event(RB_DOWN, 0, 0, 0, 0);
            mouse_event(RB_UP, 0, 0, 0, 0);
        }

        /// <summary> 왼쪽 더블클릭 발생시키기 </summary>
        public void ForceLeftDoubleClick()
        {
            mouse_event(LB_DOWN, 0, 0, 0, 0);
            mouse_event(LB_UP, 0, 0, 0, 0);

            Thread.Sleep(150);

            mouse_event(LB_DOWN, 0, 0, 0, 0);
            mouse_event(LB_UP, 0, 0, 0, 0);
        }

        /// <summary> 오른쪽 더블클릭 발생시키기 </summary>
        public void ForceRightDoubleClick()
        {
            mouse_event(RB_DOWN, 0, 0, 0, 0);
            mouse_event(RB_UP, 0, 0, 0, 0);

            Thread.Sleep(150);

            mouse_event(RB_DOWN, 0, 0, 0, 0);
            mouse_event(RB_UP, 0, 0, 0, 0);
        }

        /// <summary> 휠클릭 발생시키기 </summary>
        public void ForceMiddleClick()
        {
            mouse_event(MB_DOWN, 0, 0, 0, 0);
            mouse_event(MB_UP, 0, 0, 0, 0);
        }

        /// <summary> 휠 더블클릭 발생시키기 </summary>
        public void ForceMiddleDobuleClick()
        {
            mouse_event(MB_DOWN, 0, 0, 0, 0);
            mouse_event(MB_UP, 0, 0, 0, 0);

            Thread.Sleep(150);

            mouse_event(MB_DOWN, 0, 0, 0, 0);
            mouse_event(MB_UP, 0, 0, 0, 0);
        }

        /// <summary> 휠 올리기 </summary>
        public void ForceWheelUp(int power)
        {
            if (power > 120) power = 120;
            else if (power < -120) power = -120;

            mouse_event(WHEEL, 0, 0, power, 0);
        }

        /// <summary> 휠 내리기 </summary>
        public void ForceWheelDown(int power)
        {
            if (power > 120) power = 120;
            else if (power < -120) power = -120;

            mouse_event(WHEEL, 0, 0, -power, 0);
        }

        #endregion
    }
}


This post is licensed under CC BY 4.0 by the author.