Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing Keyboard events in C# windows service

I have created a windows service in c#. How can I call a function whenever a key is pressed, and in this function get the value of the key. I need it for both key up and key down.

My goal is to send an email if a certain series of keys were pressed. For example if you press h-e-l-l-o, no matter where you type it even on the desktop, the program should send the email.

Also, it's ok for me to implement it in another way. I need a program that runs in the background and do something when a key is pressed.

How can I do such thing? An example would be helpful.

like image 522
צח חורי Avatar asked Dec 17 '25 20:12

צח חורי


2 Answers

As somebody has already commented, a Windows service does not have a foreground window which can receive keyboard focus or Windows keyboard messages. So your only option to achieve exactly what you're after is to use a low level event hook to receive keyboard events.

Note, however, that these are system-wide events and your service might be flooded with them. They're useful in applications like screen readers and other assistive technology, but I'd recommend trying to think about whether there is some other way to do what you want to do before using this approach. For example, can you just run an application in the system tray and subscribe to WM_HOTKEY messages via calls to RegisterHotKey?

Here's an example of a low-level keyboard hook in C#.

like image 177
James Scholes Avatar answered Dec 19 '25 09:12

James Scholes


The best solution I found:
Generally author creates .NET wrapper on a low-level methods from user32.dll assembly that make using those methods quite pleasant and enjoyable.

    private LowLevelKeyboardListener _listener;        
    _listener = new LowLevelKeyboardListener();
    _listener.OnKeyPressed += _listener_OnKeyPressed;
    _listener.HookKeyboard();

    void _listener_OnKeyPressed(object sender, KeyPressedArgs e)
    {
        this.textBox_DisplayKeyboardInput.Text += e.KeyPressed.ToString();
    }

here the original link

like image 34
צח חורי Avatar answered Dec 19 '25 11:12

צח חורי



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!