Windows – Get the logged in Windows user name associated with a desktop

cdesktopwinapiwindows

I wish to enumerate all desktops in a system and get the logged in user name for that desktop. So far I have the following code snippit as an example of obtaining a HDESK handle and trying to determine the user name associated with it (if any), but the call to LookupAccountSid fails with ERROR_NONE_MAPPED ("No mapping between account names and security IDs was done").

HDESK desk = OpenDesktop( "Default", 0, FALSE, READ_CONTROL | DESKTOP_READOBJECTS );

DWORD size = 4096;

SID * sid  = (SID *)malloc( size );

GetUserObjectInformation( desk , UOI_USER_SID, sid, size, &size );

char name[512], domain[512];
int namesz = 512, domainsz = 512;

LookupAccountSid( NULL, sid, &name, &namesz, &domain, &domainsz, &s);

It might be because I am pulling out a logon SID via GetUserObjectInformation rather then a user SID. If so can I convert that to the logged in users SID?

Can anybody point me in the right direction for getting the logged in user name for an arbitrary desktop (via either it's respective HDESK or HNWD handle or even the desktop's stations HWINSTA handle)? thanks in advance.

Best Answer

If what you want is the user information then this will work.

call WTSEnumerateSessions to obtain an array of WTS_SESSION_INFO structures. for each structure, pass the SessionId member to WTSQuerySessionInformation with the WTSInfoClass member set to WTSUserName. This will give you the name of the user (if there is one) associated with the session.

Alternatively you can set the WTSInfoClass to WTSSessionInfo and get a WTSINFO structure back. This contains a lot of information including the user name and domain. Look at the header file definition of WTSINFO though as the MSDN page is wrong.

You have to call WTSEnumerateSessions twice, once to get the required buffer size and then once to get your information.

Relationships: One or more Desktop objects are in a Windows Station. A Windows Station is associated with a Session.