从 C# 中的 Windows 服务捕获关键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4251023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capture key events from a Windows Service in C#
提问by jay
I have to write an application in C# that listens to any keys being pressed. In actuality I have a bar code scanner sending the "key pressed" event, and I need to listen it... what it does from there is beyond the scope of my question.
我必须用 C# 编写一个应用程序来监听任何被按下的键。实际上,我有一个条形码扫描仪发送“按键按下”事件,我需要听它……它的作用超出了我的问题范围。
My security requirements are that there is not allowed to be any sign-onto the machine in any way shape or form AND this must run as a windows service. The user will start the machine and walk away (i.e., no desktop session).
我的安全要求是不允许以任何形式或形式对机器进行任何登录,并且这必须作为 Windows 服务运行。用户将启动机器并走开(即,没有桌面会话)。
I'm assuming I'm going to have to go unmanaged for this.
我假设我将不得不为此不受管理。
Given the security requirements is this even possible? If so, any pointers on where to start would be great.
鉴于安全要求,这甚至可能吗?如果是这样,任何关于从哪里开始的指示都会很棒。
Thanks in advance, Jay
提前致谢,杰
回答by Javed Akram
回答by Bob Moore
If you need to see keyboard presses for all apps, system-wide Hooks would be the way to go normally, but the problem is that the security changes in Vista and above make hooks rather less useful. A process cannot hook another process at a higher integrity level, so there's no guarantee you will see allevents.
如果您需要查看所有应用程序的键盘按下情况,系统范围的 Hooks 将是正常使用的方法,但问题是 Vista 及更高版本中的安全更改使 hooks 变得不太有用。一个进程不能在更高的完整性级别挂钩另一个进程,因此不能保证您会看到所有事件。
However if you only need to see events going to a particular app - the one reading the bar codes - then provided you can identify that process, a thread-specific hook will suffice and the integrity question will not arise.
但是,如果您只需要查看进入特定应用程序的事件(读取条形码的应用程序),那么只要您可以识别该进程,线程特定的挂钩就足够了,并且不会出现完整性问题。
回答by dexter
You will have to learn pInvoke with combination of learning how to look for the right events produced at the lower level of OS. By calling into user32.dll using pInvoke your managed code can filter those events through the hooks.
您将必须学习 pInvoke 并结合学习如何查找在较低级别的操作系统中生成的正确事件。通过使用 pInvoke 调用 user32.dll,您的托管代码可以通过钩子过滤这些事件。