3

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 )

svick
  • 236,525
  • 50
  • 385
  • 514
jacob
  • 1,397
  • 1
  • 26
  • 53

1 Answers1

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);
    }
}
Community
  • 1
  • 1
Kit
  • 20,354
  • 4
  • 60
  • 103