在游戏中捕获键盘?



我正在尝试用unity3d做一个按钮监控功能,但是现在遇到了一些困难。我的第一个版本的方法是通过钩子来做,一切都可以,直到我遇到英雄联盟,在这个游戏的界面上,我的键盘无法被钩子捕获。主代码如下:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelHookProc lpfn, IntPtr hMod, uint dwThreadId);
public delegate IntPtr LowLevelHookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);

接下来,我使用DirectX输入组件来监视。同样,《英雄联盟》的界面也没有任何回应。顺便说一下,我使用的是SharpDX.DirectInput。代码如下:

Keyboard keyboard;
void Start()
{
var directInput = new DirectInput();
keyboard = new Keyboard(directInput);
keyboard.Acquire();
}
void Update()
{
KeyboardState cur = keyboard.GetCurrentState();
if (cur.PressedKeys.Count != 0)
{
Debug.LogError(cur.ToString());
}
}

最后我使用GetAsyncKeyState来捕获,同样不生效。

有谁知道发生了什么吗?这种想象力不仅存在于《英雄联盟》中,也存在于其他游戏中。我还没来得及测试。如果你有任何想法或建议,我将非常感激!

已解决评论区的问题:

一些高预算游戏有反作弊系统。你必须运行你的程序以管理员身份进行按钮监控。