SystemEvents.SessionSwitch哪个用户被锁定/解锁

时间:2011-10-30 21:07:30

标签: c# .net windows winforms winapi

我正在使用SystemEvents.SessionSwitch事件来确定运行我的进程的用户是否被锁定,但该事件不会让您知道哪个用户被锁定/解锁。 如何获取此信息(来自低权限用户拥有的进程)

1 个答案:

答案 0 :(得分:0)

我认为您不能使用部分受信任的代码。如果您的应用程序或其中的一部分可以成为完全信任的服务,则可以按照the answer中的related question指定检索会话ID。

然后给定会话ID,您可以找到具有该会话ID的任何进程来获取实际用户(从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);
    }
}
相关问题