Error when using SetWindowsHookEx in Windows XP, but not in Windows 7

♀尐吖头ヾ 提交于 2019-12-06 03:10:52

问题


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:


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);


来源:https://stackoverflow.com/questions/10516448/error-when-using-setwindowshookex-in-windows-xp-but-not-in-windows-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!