我正在尝试设置一个低级别的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);
}
这在32位和64位机器上使用.NET Framework 3.5曾经能够工作,但升级到.NET Framework 4.0后在32位机器上停止工作。
有人知道如何解决这个问题,以便我可以使用4.0框架,并使其在32位和64位机器上都能工作吗?