Is it possible to write a global Keyboard Hook from windows(xp and 7) service ? ( using SetWindowsHookEx didn\'t work from a system service )
The documentation for SetWindowsHookEx
says:
or with all threads in the same desktop as the calling thread.
So you need to be associated with the same desktop (and there will be multiple desktops even without considering terminal services: the normal desktop, the secure desktop (used for UAC and login) and the screen saver).
Since services are not associated with an interactive session (and, from Windows V6, cannot be) you'll need a process within the user's session to do the hooking, and communicate with the backend service (eg. via a named pipe). And don't forget to test with no-one logged in, and multiple users logged in.
To summarize what Richard said (and to add my own commentary): You cannot directly set a global keyboard hook from a Windows service starting with Windows Vista. However, it still would be a logical choice to use a Windows service as you will have all the necessary privileges to set global hooks. You can duplicate your privileges to child processes that you create in each logged-on user's session to enable your child processes to set global hooks within their own desktop/session even if the user does not hold adequate privileges.
Personally, (assuming you're writing a keylogger) instead of aggregating all of the logged keystrokes to one process and writing them to disk, it might make sense to have each individual process write separate files according to their username.