SetWindowsHookEx fails with error 126

╄→尐↘猪︶ㄣ 提交于 2019-11-28 19:35:59

This kind of code does not work anymore on .NET 4 and up. The error code you get is otherwise descriptive, 126 = "The specified module could not be found". Which tells you that the "mar" variable contains junk.

.NET 4 had a pretty significant CLR change, it no longer pretends that jitted code lives inside unmanaged modules. So Marshal.GetHINSTANCE() does not work anymore. The code then gets sloppy, it forgets to check the return value, testing it for (IntPtr)-1 is required to detect failure and declare disaster. Pretty common for code you find at Codeproject, lots of bugs and sloppiness that can't be fixed by contributors. Not the SO model :)

SetWindowsHookEx() is a bit awkward for the low-level hooks. It requires a valid module handle, and checks it, but doesn't actually use it. This got fixed in Windows, somewhere around Win7 SP1. While certainly intended to be a useful fix, it actually made the problem worse. Because now it may work on your dev machine but not on your user's machine.

Anyhoo, the fix is simple, you just need to cough up a valid module handle. You can get one from a module that is always present in a managed app, you'll need to pinvoke LoadLibrary to get it:

var mar = LoadLibrary("user32.dll");
s_MouseHookHandle = SetWindowsHookEx(
    WH_MOUSE_LL,
    s_MouseDelegate,
    mar,
    0);

No need to call FreeLibrary(), that module stays loaded until your program terminates anyway.

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