gpt4 book ai didi

c# - 如何杀死在特定用户帐户下运行的特定进程

转载 作者:可可西里 更新时间:2023-11-01 09:57:08 25 4
gpt4 key购买 nike

如何终止在特定用户帐户下运行的特定进程。使用 C#?

谢谢,

最佳答案

var processes = from p in Process.GetProcessesByName(nameOfTheProcess)
where p.StartInfo.UserName == nameOfTheUser
select p;

foreach(Process p in processes) p.Kill();

编辑:正如 Fredrik 所指出的,UserName 属性没有为通过 GetProcesses 获得的进程设置。这是使用 WMI 获取用户名的修改版本(找到 GetProcessOwner 方法 here):

static void KillProcessByNameAndUserName(string processName, string userName)
{
var processes = from p in Process.GetProcessesByName(processName)
where GetProcessOwner(p.Id) == userName
select p;

foreach(Process p in processes) p.Kill();
}

static string GetProcessOwner(int processId)
{

string query = “Select * From Win32_Process Where ProcessID = “ + processId;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();

foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod(“GetOwner”, argList));
if (returnVal == 0)
return argList[0];
}

return “NO OWNER”;

}

关于c# - 如何杀死在特定用户帐户下运行的特定进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1011371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com