Search code examples
c#cmdprocesscommand-line-interfacepid

How can i send close command to a CMD process by PID


This process is started by selenium

So i do not have control over it how i start it

However, the CMD process have X button

Can i programmatically call that X button by PID?

enter image description here

C# 4.6.2 windows 8.1

I am able to kill the process however it is not making the same effect as X button click


Solution

  • This is part of my code using system command taskkill:

    //starts a command
    public static int RunCommandAndWait(string command, string args)
    {
        int result = -1;
    
        Process p = new Process();
        p.StartInfo.Arguments = args;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.FileName = command;
        p.StartInfo.UseShellExecute = true;
    
        if (p.Start())
        {
            p.WaitForExit();
            result = p.ExitCode;
        }
    
        p.Dispose();
        return result;
    }
    
    //kills a process using its pid and above method
    public static void KillProcessTree(int processId)
    {
        RunCommandAndWait("taskkill", String.Format("/pid {0} /f /t", processId));
        try
        {
            Process p = Process.GetProcessById(processId);
            if (p != null)
                KillProcessTree(processId); //this sometimes may be needed
        }catch(Exception)
        {
    
        }
    }