在非Windows应用程序中使用键盘挂钩C# [英] Using keyboard hooks for non-windows applications C#
问题描述
我希望能够从游戏中获取键盘输入. (即《魔兽争霸3》)
然后根据此输入,将键盘命令发送回游戏.游戏是全屏游戏.
我当前在计时器上使用GetAsyncKeyState()来告诉我上次按下的键.但是然后我无法确定是否已按下相同的键两次,因为最后按下的键将保持不变.
我需要以某种方式添加事件侦听器以用于何时按下键,而不是使用计时器来解决该问题,但是不知道如何.
要发回密钥,我试图使用SendKeys(),但发现它仅适用于Windows相关的应用程序?
我不知道SendInput()是否相同?
抱歉,如果这没有道理,我已经尝试了很多Google搜寻,但很令人沮丧.
I want to be able to get keyboard input from games. (I.e. Warcraft 3)
Then based on this input, send keyboard commands back to the game. The game is fullscreen.
I am currently using GetAsyncKeyState() on a timer to tell me what key was last pressed. But then I cant tell if the same key has been pressed twice because the last key pushed will remain the same.
I need to add an event listener somehow for when a key is pushed, instead of a timer to solve that problem, but don''t know how.
To send keys back, I was trying to use SendKeys(), but found out it only works on windows related applications?
I don''t know if SendInput() is the same?
Sorry if this doesn''t make sense, I''ve tried lots of googling, and it is frustrating.
推荐答案
不,SendInput
是不同的, 到目前为止.简而言之,SendKeys
是非常有限的(我想说,它几乎没有用,通常是一些松散者在不知道如何以合法方式编写UI的情况下,将它们用作所编写的同一应用程序的解决方法)方法 :-)).关于SendInput
,它是非常低级的.调用它时,无论它是什么,输入都会分派到某个活动窗口.
您可以通过P/Invoke在C#中轻松使用此功能,因为所有的辛苦工作已经为您完成.此处:
http://www.pinvoke.net/default.aspx/user32/SendInput.html [ ^ ].
P/Invoke的替代方法是使用C ++/CLI.您可以创建混合模式(托管+非托管)项目,使用任何C ++非托管API,将所有非托管代码包装在C ++/CLI引用"或值"类/结构中并公开.此类项目的输出可以用作常规的.NET程序集,例如,由您的C#项目引用.
我希望您理解通过P/Invoke或C ++/CLI使用原始Windows API会破坏应用程序的平台兼容性.
您可以在C#项目中安装Windows挂钩,但不能将其作为全局挂钩安装.根据Microsoft文档,该挂钩应安装在单独的DLL中.当然,它应该是不受管的DLL.
—SA
No,SendInput
is not the same, by far. In brief,SendKeys
is very limited (I would say, it''s pretty much useless, typically used by some loosers as a workaround on the same application they write if they don''t know how to write UI in a legitimate way :-)). As to theSendInput
, it is very low-level. When you call it, the input is dispatched to some active window, no matter what it is.
You can easily use this function in C# through P/Invoke, because all the hard work is already done for you. Here:
http://www.pinvoke.net/default.aspx/user32/SendInput.html[^].
The approach alternative to P/Invoke is using C++/CLI. You can create a mixed-mode (managed+unmanaged) project, use any C++ unmanaged API, wrap all the unmanaged code in C++/CLI "ref" or "value" classes/structures and make the public. The output of such project can be uses as a regular .NET assembly, for example, referenced by your C# project.
I hope you understand that using raw Windows API through P/Invoke or C++/CLI breaks platform compatibility of your application.
You can install a Windows Hook in C# project, but you cannot install it as a global hook. According to Microsoft documentation, the hook should be installed in a separate DLL. It should be an unmanaged DLL, of course.
—SA
这篇关于在非Windows应用程序中使用键盘挂钩C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!