C# 获取系统进程的用户名
程序员文章站
2022-07-22 09:23:47
需要添加对 system.management.dll 的引用 复制代码 代码如下:using system.diagnostics; using system.manag...
需要添加对 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));
}
console.readkey();
}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;
}