views:

697

answers:

3

"User A" is logged on My application recognizes Environment.Username as "User A"

Now in Windows, I click on Switch user ... "User B" logs on

"User A's" processes are still running Application run by "User A" still says Environment.Username is "User A" I want the application to recognize that the currently logged on user (currently active user) is "User B"

How do I do this?

+1  A: 

You definitely wont be finding the information at that level - you want to go to lower level APIs that enuemrate the logged on users (of which there can be more than one).

Something like How to write an application that supports the Fast User Switching feature by using Visual Basic .NET or Visual Basic 2005 in Windows XP ?

See also Architecture of Fast User Switching

Ruben Bartelink
+3  A: 

There is no such thing as the currently active user since there can be more than one (Terminal server)

You can use GetSystemMetrics(SM_REMOTESESSION) to check if this a "local" session, and WTSGetActiveConsoleSessionId to get the session id of the console session (Currently logged on user as you call it) You can use WTSRegisterSessionNotification to get notified when this changes. ProcessIdToSessionId(GetCurrentProcess(),...) will get you the session id your process is in. Finally, WTSQuerySessionInformation() will get you info about a specific session.

Anders
+1: Exactly. Even within a single session or process (e.g. server process doing user impersonation) there can be multiple user identities.
Richard
Ugh, community wiki somehow got checked, oh well
Anders
+3  A: 
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT UserName FROM Win32_ComputerSystem");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                loggedOnUserName = queryObj["UserName"].ToString();
                loggedOnUserName = loggedOnUserName.Substring(loggedOnUserName.LastIndexOf('\\') + 1);
            }

When "User B" is logged on, the application running under "User A" reports "User B" in loggedOnUserName.

That's what I was looking for. Thanks anyways.

SaM