在32位计算机上编译.NET 4.0框架时,SetWindowsHookEx返回0

ebl*_*ght 8 keyboard-hook com-interop setwindowshookex c#-4.0

即使应用程序没有对焦,我也试图设置一个低级别的Windows键盘钩子来抓住三个按键.为此,我将SetWindowsHookEx称为

// Create an instance of HookProc.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
hKeyboardHook = SetWindowsHookEx(
    WH_KEYBOARD_LL,
    KeyboardHookProcedure,
    Marshal.GetHINSTANCE(
        Assembly.GetExecutingAssembly().GetModules()[0]),
    0);
//If SetWindowsHookEx fails.
if (hKeyboardHook == 0)
{
    //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
    int errorCode = Marshal.GetLastWin32Error();
    //do cleanup
    Stop(false, true, false);
    //Initializes and throws a new instance of the Win32Exception class with the specified error. 
    throw new Win32Exception(errorCode);
}
Run Code Online (Sandbox Code Playgroud)

这曾经使用.NET Framework 3.5在32位和64位计算机上运行,​​但在升级到.NET Framework 4.0后停止在32位计算机上运行.

有谁知道如何解决这个问题,以便我可以使用4.0 Framework并在32位和64位机器上运行?

小智 24

像这样导入dll:

[DllImport("kernel32.dll")]
    public static extern IntPtr GetModuleHandle(string name); 
Run Code Online (Sandbox Code Playgroud)

然后用

GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName)
Run Code Online (Sandbox Code Playgroud)

取代

Marshal.GetHINSTANCE(
    Assembly.GetExecutingAssembly().GetModules()[0]
Run Code Online (Sandbox Code Playgroud)