简体   繁体   English

使用MouseKeyHook时,KeyPress事件未触发

[英]KeyPress event not firing when using MouseKeyHook

I started using MouseKeyHook library couple of days ago to intercept keyboard buttons for an application that we're building (the application uses numerical keyboard as input to send specific messages through Akka, etc). 几天前我开始使用MouseKeyHook库拦截我们正在构建的应用程序的键盘按钮(应用程序使用数字键盘作为输入通过Akka发送特定消息等)。

I've managed to get it to work pretty quickly using a console app and registering everything there, but once I moved the implementation into a specific service, it stopped working (event is not being fired). 我已经成功地使用控制台应用程序并在那里注册了所有内容,但是一旦我将实现移动到特定服务中,它就停止了工作(事件没有被触发)。

Here's the code example: 这是代码示例:

public class KeypadService : IKeypad
{
    private readonly IKeyboardEvents _keyboardEvents;

    public KeypadService()
    {
        _keyboardEvents = Hook.GlobalEvents();
        _keyboardEvents.KeyPress += GlobalHookKeyPress;
    }

    public void Enable(Action<string> codeEntered)
    {

    }

    public void Disable()
    {
        _keyboardEvents.KeyPress -= GlobalHookKeyPress;
    }

    private static void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
    {
        // Do something
    }
}

KeypadService is created by Autofac at the start of the application (and the startup application is a console app). KeypadService由Autofac在应用程序启动时创建(启动应用程序是控制台应用程序)。

builder.RegisterType<KeypadService>().As<IKeypad>().SingleInstance();

The constructor is being hit and everything executes inside the constructor. 构造函数被命中,一切都在构造函数内执行。

Any clue as to why it might not be firing? 任何线索,为什么它可能不会被解雇? Any help is appreciated! 任何帮助表示赞赏!

My assumption is that you are that you are trying to hook keyboards from a windows service. 我的假设是你是在尝试从Windows服务中挂钩键盘。 If so there is a problem. 如果是这样则有问题。

Brief explanation: Windows hooks need to have a so called "interactive session" in order to work properly. 简要说明: Windows挂钩需要有一个所谓的“交互式会话”才能正常工作。 An interactive session is created whenever a user is logged in. Since more than one users can be logged into a windows machine there are sometimes more than one interactive sessions, sometimes none. 每当用户登录时都会创建一个交互式会话。由于多个用户可以登录到Windows机器,因此有时会有多个交互式会话,有时甚至没有。 Services run independently from interactive sessions, they even run when no one is logged in. 服务独立于交互式会话运行,甚至在没有人登录时运行。

See this thread for detailed explanation: Global Keyboard Hook from windows service windows-service 有关详细说明,请参阅此主题: 来自Windows服务 Windows服务的全局键盘挂钩

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM