Recipe: Detect Console Session in Windows

Posted on 10 January 2012 by Joseph

Working on an upcoming version of my company’s software Granola today, I came upon the need to determine whether the program was running in the so-called “console session.aspx)” – the session in which the user is physically sitting at the terminal. The context of my interest was Windows XP power management, but I can think of other reasons, like changing the user interface based on the physical location and logon status of the user.

As with many things Windows, the solution is quite simple but the documentation quite sparse. Googling eventually brought me to the WTSGetActiveConsoleSessionId.aspx) and ProcessIdToSessionId.aspx) functions. The former retrieves the session ID for the console session, and the latter queries the session ID for a given process. Pass in the current process ID and compare the values to perform the required test:

bool check_console(){
    DWORD sid;
    ProcessIdToSessionId(GetCurrentProcessId(), &sid);
    if(sid == WTSGetActiveConsoleSessionId()){
        return true;
    }
    return false;
}

For more fine-grained control, you can register to receive session change messages with the WTSRegisterSessionNotification.aspx) function. Given a window handle, the following code will register for all session change notifications:

if(WTSRegisterSessionNotification(handle, NOTIFY_FOR_ALL_SESSIONS) != TRUE){
    // handle error (GetLastError)
}

Change NOTIFY_FOR_ALL_SESSIONS to NOTIFY_FOR_THIS_SESSION to only receive session changes for the current console. Once the registration has occurred, session changes will generate WM_WTSSESSION_CHANGE.aspx) message; your application can then respond to these messages as needed.

comments powered by Disqus

Copyright © 2018 Joseph Turner