4

有没有办法从我的 .NET 程序中检测它是作为桌面用户正常运行还是使用“作为不同用户运行”菜单选项/runas 命令作为不同用户运行?

4

1 回答 1

4

获取运行程序的用户更容易,您可以使用Environment.UserNameSystem.Security.Principal.WindowsIdentity.GetCurrent().Name
它们之间的区别的链接位于下面...

现在,获取登录用户有点棘手。
我使用以下方法(我想我不久前在这里找到了它)。它所做的是检查谁是explorer.exe进程的所有者(即登录用户):

private string GetExplorerUser()
{
    var query = new ObjectQuery(
        "SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");

    var explorerProcesses = new ManagementObjectSearcher(query).Get();

    foreach (ManagementObject mo in explorerProcesses)
    {
       String[] ownerInfo = new string[2];
       mo.InvokeMethod("GetOwner", (object[])ownerInfo);

       return String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
    }

    return string.Empty;
}

上面的方法需要System.Managmentdll

更新: 上面的方法工作正常,基于 OP 的评论 - 添加了另一个选项:

从以下位置获取第一个用户名Win32_ComputerSystem

 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
 ManagementObjectCollection collection = searcher.Get();
 string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
于 2013-02-26T13:14:11.133 回答