我的 c# 应用程序创建了用于处理键盘事件的键盘钩子(许多读卡器、扫描仪和其他 POS 设备模拟键盘)。有时我的应用程序会创建没有错误的键盘钩子,但它不会触发事件并且在处理时抛出异常:
System.ComponentModel.Win32Exception (0x80004005):无法删除“应用程序”的键盘挂钩。错误 1404:无效的钩子句柄
其他日志条目是相同的错误,但它讲述了
ERROR_NOT_ALL_ASSIGNED
我无法在我的电脑上重现这个问题,也不知道我应该调查什么或谷歌。我知道:
另外,我不熟悉非托管代码和 win api。我从某个线程中获得了这段代码,并根据我的需要对其进行了修改,但在高级抽象上进行了修改。
挂钩演员:
public GlobalKeyboardHook()
{
_windowsHookHandle = IntPtr.Zero;
_user32LibraryHandle = IntPtr.Zero;
_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.
_user32LibraryHandle = LoadLibrary("User32");
if (_user32LibraryHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode,
$"Failed to load library 'User32.dll'. Error {errorCode}: …Run Code Online (Sandbox Code Playgroud)