检测键盘或鼠标事件是否由软件触发

Detect if keyboard or mouse events are triggered by a software

有没有办法确定键盘或鼠标事件是从硬件触发的,还是从 Windows 上的桌面应用程序 运行 中的应用程序(如 TeamViewer、Steam 或其他远程桌面软件)触发的? ]?

我的目的不是防止机器人,而是防止远程访问应用程序。

RawInput API 似乎可以让我检测到使用 SendInput API 发送的虚假事件。正确吗?

SetWindowsHookEx() 提供的低级 keyboard/mouse 挂钩报告输入是由实际设备生成还是由应用程序代码注入。

对于 low-level keyboard hook, the hook provides a pointer to a KBDLLHOOKSTRUCT 结构,它有一个 flags 成员,其中包含一个 LLKHF_INJECTED 标志用于假输入。

对于一个 low-level mouse hook, the hook provides a pointer to a MSLLHOOKSTRUCT 结构,它有一个 flags 成员,其中包含一个 LLMHF_INJECTEDLLMHF_LOWER_IL_INJECTED 标志用于假输入。

任何一个挂钩都可以 return 一个非零值来阻止输入被传递到挂钩链的其余部分,从而阻止传递到目标 window.

关于原始输入 API,根据(an older version of 1) the documentation for the GetRawInputDeviceInfo() 函数:

hDevice [in, optional]
Type: HANDLE

A handle to the raw input device. This comes from the lParam of the WM_INPUT message, from the hDevice member of RAWINPUTHEADER, or from GetRawInputDeviceList. It can also be NULL if an application inserts input data, for example, by using SendInput.

1: 高亮的注释在当前版本的文档中被去掉了,不知道为什么。

因此,WM_INPUT 消息报告的 hDevice 对于虚假输入将为 NULL。

但是,无法使用原始输入 API 阻止输入。你仍然需要一个低级的钩子。