以编程方式杀死C#中vista/windows 7中的进程

mmr*_*mmr 9 c# kill process windows-vista

我想在vista/windows 7中以编程方式杀死一个进程(我不确定两者之间的UAC实现是否存在重大问题以产生影响).

现在,我的代码看起来像:

  if(killProcess){
      System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("MyProcessName");
       // Before starting the new process make sure no other MyProcessName is running.
        foreach (System.Diagnostics.Process p in process)
        {
            p.Kill();
        }

        myProcess = System.Diagnostics.Process.Start(psi);
   }
Run Code Online (Sandbox Code Playgroud)

我必须这样做,因为我需要确保如果用户崩溃程序或突然退出,则在重新启动应用程序时重新启动此辅助进程,或者如果用户想要更改此辅助进程的参数.

该代码在XP中运行良好,但在Windows 7(我假设在Vista中)失败时出现"访问被拒绝"消息.从全能的Google告诉我的内容来看,我需要以管理员的身份运行我的杀戮程序以解决这个问题,但这只是一个弱点.另一个可能的答案是使用LinkDemand,但我不理解LinkDemand的msdn页面,因为它与进程有关.

我可以将代码移动到一个线程中,但是它有许多固有的其他困难,我真的不想发现它.

And*_*ley 5

您是对的,因为您没有管理权限。您可以通过在本地系统用户下安装服务并根据需要对其运行自定义命令来解决此问题。

在您的 Windows 窗体应用程序中:

private enum SimpleServiceCustomCommands { KillProcess = 128 };

ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, "SERVICE_NAME");
scp.Assert();
System.ServiceProcess.ServiceController serviceCon = new System.ServiceProcess.ServiceController("SERVICE_NAME", Environment.MachineName);
serviceCon.ExecuteCommand((int)SimpleServiceCustomCommands.KillProcess);

myProcess = System.Diagnostics.Process.Start(psi);
Run Code Online (Sandbox Code Playgroud)

在您的服务中:

private enum SimpleServiceCustomCommands { KillProcess = 128 };

protected override void OnCustomCommand(int command)
{
    switch (command)
    {
        case (int)SimpleServiceCustomCommands.KillProcess:
            if(killProcess)
            {
                System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("MyProcessName");
                // Before starting the new process make sure no other MyProcessName is running.
                foreach (System.Diagnostics.Process p in process)
                {
                    p.Kill();
                }
            }
            break;
        default:
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)