【发布时间】:2011-10-30 21:07:30
【问题描述】:
我正在使用 SystemEvents.SessionSwitch 事件来确定运行我的进程的用户是否被锁定,但该事件不会让您知道哪个用户被锁定/解锁。 我怎样才能获得这些信息(来自低权限用户拥有的进程)
【问题讨论】:
标签: c# .net windows winforms winapi
我正在使用 SystemEvents.SessionSwitch 事件来确定运行我的进程的用户是否被锁定,但该事件不会让您知道哪个用户被锁定/解锁。 我怎样才能获得这些信息(来自低权限用户拥有的进程)
【问题讨论】:
标签: c# .net windows winforms winapi
我认为您不能使用部分受信任的代码。如果您的应用程序或其中的一部分可以成为完全信任的服务,则可以按照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);
}
}
【讨论】: