10

我想在 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);
   }

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

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

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

4

2 回答 2

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);

在您的服务中:

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;
    }
}
于 2009-02-13T04:25:20.690 回答
0

我将为 Simon Buchan 的建议添加代码。这是有道理的,并且应该也可以工作,假设您的 Windows 窗体首先启动了该过程。

这是您创建流程的地方。注意变量 myProc。这就是你的处理方式:

System.Diagnostics.Process myProc = new System.Diagnostics.Process();
myProc.EnableRaisingEvents=false;
myProc.StartInfo.FileName="PATH_TO_EXE";
myProc.Start();

稍后,只需使用以下命令将其杀死:

myProc.Kill();
于 2009-02-13T05:30:25.540 回答