我试图设置一个低级的Windows键盘 Hook ,以捕获三个按下的键,即使该应用程序未处于焦点状态也是如此。为此,我将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);
}
这曾经在使用.NET Framework 3.5的32位和64位计算机上运行,但是在升级到.NET Framework 4.0之后,停止在32位计算机上运行。
有谁知道如何解决此问题,以便我可以使用4.0框架并使它在32位和64位计算机上都能正常工作?
最佳答案
像这样导入dll:
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string name);
然后使用
GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName)
取代
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]
关于c#-4.0 - 在32位计算机中为.NET 4.0框架进行编译时,SetWindowsHookEx返回0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3567758/