views:

1228

answers:

4

What win32 calls can be used to detect key press events globally (not just for 1 window, I'd like to get a message EVERY time a key is pressed), from a windows service?

A: 

I don't directly know the answer, but I would try to find an open-source Key Logger for Windows. From there, you should be able to find how it is speicfically implemented in a Win32 environment.

First result on Google: link text

Matthew Ruston
+2  A: 

You want to use Win32 Hooks. In particular a keyboard hook.

You can read more about it here

The type of hook you want is WH_KEYBOARD and you can set it via the Win32 API SetWindowsHookEx.

Basically windows will call a function in a dll that you create everytime a key is pressed in any application system wide.

The hook will call your function which will have this interface:

LRESULT CALLBACK KeyboardProc(      
    int code,
    WPARAM wParam,
    LPARAM lParam
);

More information about this callback here.

With windows hooks you can not only track system wide events across all processes, but you can also filter them and stop them altogether.

Brian R. Bondy
+2  A: 

Take a look at the hooks you can set with SetWindowHookEx:

http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx

However, unless you are running an "interactive" service, you won't have access to the desktop (and you shouldn't be running an interactive service because it won't work right in newer versions of Windows). You will have to look into the session and desktop management APIs in order to access the desktop/console.

jdigital
A: 

Check out the Raw Input API in MSDN:

http://msdn.microsoft.com/en-us/library/ms645536(VS.85).aspx

It allows you to get input from keyboards (among other things) without messing around with global hooks. Global hooks should only be used as a last resort as they may introduce unintended consequences.

The only drawback to using Raw Input is that it may not properly receive keystrokes which are generated by software.

Kennet Belenky