Reputation: 401
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.
Upvotes: 3
Views: 6167
Reputation: 401
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();
}
Upvotes: 1
Reputation: 7926
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#.
Upvotes: 1