我正在使用 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/