c#でフックを設定してマウスの移動を監視
6107 ワード
1 using System;
2 using System.Windows.Forms;
3 using System.Runtime.InteropServices;
4 namespace HotelManage
5 {
6 public partial class Form1 : Form
7 {
8 public Form1()
9 {
10 InitializeComponent();
11 }
12 void hook_onMouseChange(object sender, EventArgs e)
13 {
14 this.Text = Cursor.Position.ToString();
15 }
16 private void Form1_Load(object sender, EventArgs e)
17 {
18 Win32Hook hook = new Win32Hook();
19 hook.onMouseChange += new EventHandler(hook_onMouseChange);
20 hook.SetHook();
21 }
22 }
23 public class Win32Hook
24 {
25 [DllImport("kernel32")]
26 public static extern int GetCurrentThreadId();
27 [DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
28 public static extern int SetWindowsHookEx(
29 HookType idHook,
30 HOOKPROC lpfn,
31 int hmod,
32 int dwThreadId);
33 public enum HookType
34 {
35 WH_GETMESSAGE = 3
36 }
37 public delegate int HOOKPROC(int nCode, int wParam, int lParam);
38 public event System.EventHandler onMouseChange;
39 public void SetHook()
40 {
41 SetWindowsHookEx(HookType.WH_GETMESSAGE,
42 new HOOKPROC(this.MyKeyboardProc),
43 0,
44 GetCurrentThreadId());
45 }
46 public int MyKeyboardProc(int nCode, int wParam, int lParam)
47 {
48 if (onMouseChange != null)
49 {
50 onMouseChange(null, null);
51 }
52 return 0;
53 }
54 }
55 }