发布:2022/12/17 13:36:51作者:管理员 来源:本站 浏览次数:602
需要添加对 System.Management.dll 的引用
using System.Diagnostics;
using System.Management;
static void Main(string[] args)
{
foreach (Process p in Process.GetProcesses())
{
Console.Write(p.ProcessName);
Console.Write("----");
Console.WriteLine(GetProcessUserName(p.Id));//根据进程的ID获得进程的用户名
}
Console.ReadKey();
}
/// <summary>
/// 获得进程的用户名
/// </summary>
/// <param name="pID"></param>
/// <returns></returns>
private static string GetProcessUserName(int pID)
{
string text1 = null;
SelectQuery query1 =
new SelectQuery("Select * from Win32_Process WHERE processID=" + pID);
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1);
try
{
foreach (ManagementObject disk in searcher1.Get())
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
inPar = disk.GetMethodParameters("GetOwner");
outPar = disk.InvokeMethod("GetOwner", inPar, null);
text1 = outPar["User"].ToString();
break;
}
}
catch
{
text1 = "SYSTEM";
}
return text1;
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4