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

标签 c# .net windows winforms winapi

我正在使用 SystemEvents.SessionSwitch 事件来确定运行我的进程的用户是否被锁定,但该事件不会让您知道哪个用户被锁定/解锁。 我怎样才能得到这个信息(从一个低特权用户拥有的进程)

最佳答案

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

然后给定 session ID,您可以找到任何具有该 session 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);
    }
}

关于c# - SystemEvents.SessionSwitch 哪个用户被锁定/解锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947820/

相关文章:

c# - 无法使用集合初始值设定项初始化类型 'SelectListItem',因为它未实现 'System.Collections.IEnumerable'

c# - Rx IObservable 仅在值发生一定幅度变化时才产生值

.net - Environment.OSVersion 不存在

c# - 如何让 "Copy to Output Directory"与单元测试一起使用?

windows - Windows 上的 Perl GUI 编程

java - 在其自己的 cmd.exe 中运行工具

c# - GridView LinkBut​​ton 在 C# 中搜索后不更改 CommandArgument 的值

c# - 如何在使用 Active Directory 角色和身份验证提供程序时提供 ASP.NET 表单例份验证 UX?

c# - 远程服务器返回错误 : (401) Unauthorized

python - 仅在 python 打印结束时执行 LF(换行)