SetWindowsHookEx returns 0 when compiling for the .NET 4.0 framework in 32bit machines

送分小仙女□ 提交于 2019-11-29 04:26:51
DsaIc

import the dll like this:

[DllImport("kernel32.dll")]
    public static extern IntPtr GetModuleHandle(string name); 

then use

GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName)

to replace

Marshal.GetHINSTANCE(
    Assembly.GetExecutingAssembly().GetModules()[0]

From the documentation for SetWindowsHookEx

hMod [in]
HINSTANCE
A handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.

So you should be passing in IntPtr.Zero for NULL

//install hook
  hKeyboardHook = SetWindowsHookEx(
    WH_KEYBOARD_LL,
    KeyboardHookProcedure,
    IntPtr.Zero,
    0);

Solved it by targeting each platform separately. Configured VS to compile both a Win32 and a Win64 version and deploying on x86 and x64 machines their corresponding binary.

The Win32 or x86 runs on both 32bit and 64bit machines.

OhMyGeo

Hans Passant:

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