简体   繁体   中英

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).

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).

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. If so there is a problem.

Brief explanation: Windows hooks need to have a so called "interactive session" in order to work properly. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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