Error when using SetWindowsHookEx in Windows XP, b

2019-04-08 16:34发布

I have develop a application that use a global keybord/mouse hook. It works perfect in Windows 7, but not in Windows XP.

When I call SetWindowsHookEx in Windows XP, I get error code 1428

int MouseLowLevel   = 14
int code = SetWindowsHookEx(MouseLowLevel,
                 MouseHookProc,
                 IntPtr.Zero,
                 0);

private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) {}

1条回答
Viruses.
2楼-- · 2019-04-08 17:03

Curious that this code doesn't fail on Win7 but I certainly never tried. But it is correct behavior, looks like they improved it. The argument validation for SetWindowsHookEx() requires a valid non-zero 3rd or 4th argument. The error code is highly descriptive, from WinError.h:

//
// MessageId: ERROR_HOOK_NEEDS_HMOD
//
// MessageText:
//
// Cannot set nonlocal hook without a module handle.
//
#define ERROR_HOOK_NEEDS_HMOD            1428L

Any module handle will do since it doesn't actually get used for low-level hooks, no DLL needs to be injected to make them work. Some care in selecting one is required for .NET 4 since its CLR no longer fakes module handles for pure managed assemblies. A good one to use is the one you get out of pinvoking LoadLibrary("user32.dll") since it is always already loaded. You don't have to call FreeLibrary().

You'll need this declaration to call LoadLibrary:

[DllImport("kernel32", SetLastError=true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadLibrary(string fileName);
查看更多
登录 后发表回答