Skip to content

Commit b7a98c2

Browse files
committed
added pinvoke error-checking
1 parent 4749ed0 commit b7a98c2

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

RetailCoder.VBE/Common/KeyboardHook.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,12 @@ public void Attach()
6565
return;
6666
}
6767

68-
_hookId = User32.SetWindowsHookEx(WindowsHook.KEYBOARD, HookCallback, Kernel32.GetModuleHandle("user32"), 0);
68+
var handle = Kernel32.GetModuleHandle("user32");
69+
if (handle == IntPtr.Zero)
70+
{
71+
throw new Win32Exception();
72+
}
73+
_hookId = User32.SetWindowsHookEx(WindowsHook.KEYBOARD, HookCallback, handle, 0);
6974
if (_hookId == IntPtr.Zero)
7075
{
7176
throw new Win32Exception();
@@ -81,7 +86,10 @@ public void Detach()
8186
return;
8287
}
8388

84-
User32.UnhookWindowsHookEx(_hookId);
89+
if (!User32.UnhookWindowsHookEx(_hookId))
90+
{
91+
throw new Win32Exception();
92+
}
8593

8694
IsAttached = false;
8795
Debug.WriteLine("{0}: {1}", GetType().Name, IsAttached ? "Attached" : "Detached");

RetailCoder.VBE/Common/MouseHook.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,17 @@ public void Attach()
4444
return;
4545
}
4646

47-
_hookId = User32.SetWindowsHookEx(WindowsHook.MOUSE, HookCallback, Kernel32.GetModuleHandle("user32"), 0);
47+
var handle = Kernel32.GetModuleHandle("user32");
48+
if (handle == IntPtr.Zero)
49+
{
50+
throw new Win32Exception();
51+
}
52+
_hookId = User32.SetWindowsHookEx(WindowsHook.MOUSE, HookCallback, handle, 0);
4853
if (_hookId == IntPtr.Zero)
4954
{
5055
throw new Win32Exception();
5156
}
52-
53-
57+
5458
IsAttached = true;
5559
Debug.WriteLine("{0}: {1}", GetType().Name, IsAttached ? "Attached" : "Detached");
5660
}
@@ -62,7 +66,10 @@ public void Detach()
6266
return;
6367
}
6468

65-
User32.UnhookWindowsHookEx(_hookId);
69+
if (!User32.UnhookWindowsHookEx(_hookId))
70+
{
71+
throw new Win32Exception();
72+
}
6673

6774
IsAttached = false;
6875
Debug.WriteLine("{0}: {1}", GetType().Name, IsAttached ? "Attached" : "Detached");

0 commit comments

Comments
 (0)