I am using the following code to get the Current user and the owner of my application's process.
Current User:
CurrentUser = WindowsIdentity.GetCurrent().Name;
Process Owner:
String strQuery = String.Format("Select * From Win32_Process where Name='{0}'", ProcessName);
ObjectQuery oQuery = new ObjectQuery(strQuery);
ManagementObjectSearcher oManSearcher = new ManagementObjectSearcher(oQuery);
foreach (ManagementObject oManItem in oManSearcher.Get())
{
String[] s = new String[2];
oManItem.InvokeMethod("GetOwner", (object[])s);
ProcessOwner = s[0];
break;
}
I need to determine grammatically, which user account the instance of my application runs in.
Basically, I allow one instance of my application per logged in user.
The above code works, when a user launches the application normally. The code breaks down, when a user right clicks on a shortcut (or using a similar method) and selects "run as administrator". The process owner in this case will not be the logged in user, but rather that of the administrator.
That wreaks havoc in determining a multiple instance, not to mention the proper database path, etc.
From my perspective, an instance launched normally and an instance launched as an administrator are both instances under the same logged in user, just the owner is different.
How do I determine what logged in user a process belongs to? Checking process owner to the current user is not, as stated, always the best check.
ANSWER:
Here is the completed method, developed from the selected answer.
public static String GetUsernameBySessionId(int sessionId, Boolean prependDomain)
{
IntPtr buffer;
int strLen;
String username = "SYSTEM";
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSUserName, out buffer, out strLen) && strLen > 1)
{
username = Marshal.PtrToStringAnsi(buffer);
WTSFreeMemory(buffer);
if (prependDomain)
{
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1)
{
username = String.Format("{0}\\{1}", Marshal.PtrToStringAnsi(buffer), username);
WTSFreeMemory(buffer);
}
}
}
return username;
}
The current process SessionId is:
Process.GetCurrentProcess().SessionId
To get the logged in user of an application I would suggest to read the SessionId of the current process that is independent from the user actually running the application. The SessionId of a process can be read with:
The username associated with a SessionId can be retrieved using the function from this answer: Get Windows user name from SessionID .
The function
GetUsernameBySessionId
also requires this enumeration: