programmatically kill a process in vista/windows 7 in C#

后端 未结 2 1870
忘掉有多难
忘掉有多难 2020-12-17 20:40

I want to kill a process programmatically in vista/windows 7 (I\'m not sure if there\'s significant problems in the implementation of the UAC between the two to make a diffe

2条回答
  •  星月不相逢
    2020-12-17 21:15

    You are correct in that it's because you don't have administrative priveleges. You can solve this by installing a service under the local system user and running a custom command against it as needed.

    In your windows form app:

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

    In your service:

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

提交回复
热议问题