4

Is there a way to detect from my .NET program whether it is being run as the desktop user normally or being run as a different user using the "run as a different user" menu option/runas command?

fangster
  • 361
  • 2
  • 9

1 Answers1

4

Getting the user which ran the program is easier, you can use Environment.UserName or System.Security.Principal.WindowsIdentity.GetCurrent().Name.
Links to the difference between them are located below...

Now, getting the logged in user is a little more tricky.
I use the following method (I think I found it here in SO a while back). What it does is check who is the owner of the explorer.exe process (which is the logged in user):

private string GetExplorerUser()
{
    var query = new ObjectQuery(
        "SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");

    var explorerProcesses = new ManagementObjectSearcher(query).Get();

    foreach (ManagementObject mo in explorerProcesses)
    {
       String[] ownerInfo = new string[2];
       mo.InvokeMethod("GetOwner", (object[])ownerInfo);

       return String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
    }

    return string.Empty;
}

The method above requires the System.Managment dll

Update: Method above works fine, based on OP's comments - added another option :

Getting first username from Win32_ComputerSystem:

 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
 ManagementObjectCollection collection = searcher.Get();
 string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
Blachshma
  • 17,097
  • 4
  • 58
  • 72
  • Thanks very much. Unfortunately the reason I want to know this is to launch explorer when a different user with the /separate switch but normally when not! – fangster Feb 26 '13 at 14:22
  • Thanks, any suggestions though? I may be being stupid but I'm staring at task manager and can't see a suitable process. – fangster Feb 26 '13 at 15:44
  • Added another option for use to use. – Blachshma Feb 26 '13 at 19:22