I am using SystemEvents.SessionSwitch event to determined if the user running my process got locked, but the event does not let you know which user got locked/unlocked. How can I get this information (from a process owned by a low privileged user )
Asked
Active
Viewed 1,386 times
1 Answers
0
I don't think you can for partially trusted code. If your application or part of it could be made into a full-trust service, the session ID could be retrieved as specified in the answer to a related question.
Then given the session ID, you could find any process with that session ID to get the actual user (abstracted from Getting Windows Process Owner Name):
[DllImport ("advapi32.dll", SetLastError = true)]
static extern bool OpenProcessToken (IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport ("kernel32.dll", SetLastError = true)]
[return: MarshalAs (UnmanagedType.Bool)]
static extern bool CloseHandle (IntPtr hObject);
static uint TOKEN_QUERY = 0x0008;
// ...
public static WindowsIdentity GetUserFromSession(int sessionId)
{
return Process.GetProcesses()
.Where(p => p.SessionId == sessionId)
.Select(GetUserFromProcess)
.FirstOrDefault();
}
public static WindowsIdentity GetUserFromProcess(Process p)
{
IntPtr ph;
try
{
OpenProcessToken (p.Handle, TOKEN_QUERY, out ph);
return new WindowsIdentity(ph);
}
catch (Exception e)
{
return null;
}
finally
{
if (ph != IntPtr.Zero) CloseHandle(ph);
}
}