Search code examples
c++windowsserviceremote-desktop

How to connect a Windows Service to the Console session


I've been developing a remote desktop application which runs as a Windows service, and I was wondering how I could connect the application to a specific session, and allow it to retrieve the user's desktop as a bitmap, set the cursor position, send mouse clicks, and keyboard input to the console session.


Solution

  • You need to use SetThreadDesktop() to change the thread's context in your service to the user's desktop.

    • SetThreadDesktop() takes a handle to the desktop as it's first parameter; to get that handle, use EnumDesktops().
    • EnumDesktops() takes a handle to the window station as it's first parameter; to get that handle, use EnumWindowStations()

    To understand what's going on with Window Stations and Desktops, try reading this overview from from MSDN.

    Finally, be cautious with this technique. Higher-privileged processes (i.e., services) interacting with the user's desktop are the basis for shatter attacks.