简体   繁体   中英

Stop command line process started in C# on Close of Application

I have started a process in my C# application on a button click event as below,

System.Diagnostics.Process process = new System.Diagnostics.Process();
private void btnOpenPort_Click(object sender, RoutedEventArgs e)
{
    System.Diagnostics.ProcessStartInfo startInfo = new 
    System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    startInfo.FileName = "http-server";
    // startInfo.Arguments = "/C http-server -p 8765";
    this.process.StartInfo = startInfo;
    this.process.Start();                     
}

Now, I want to Stop this Command-line process on the close of the application windows. As if I write a command in Command Prompt, I usually press Ctrl + C to stop the execution.

Edit: I have this event, fired when clicked on a close button.

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Int32 result = DllWrapper.HdsDestroy();
    MessageBox.Show("Destroy result = " + (result == 0 ? "Success" : "Fail"));
}

I found a solution on the Internet, SendKeys but I couldn't understand it. PS: It might be duplicate of some questions but some of them won't work for me.

Thank you in Advance

Thanks to @mjwills for guiding me.

Later, I figured out that process.Start() in this case, started two different processes. One is cmd.exe and another is node.exe .

process.Kill() only kill the cmd.exe . So, I have figured it out that I have to find that node.exe process and kill it too.

I have two solutions :

1. This might stop all the process named node.exe but for now, this worked for me.

foreach(var node in Process.GetProcessesByName("node"))
{
   node.Kill();
}

2. As I mentioned in my question, Use SendKeys.SendWait("^(C)"); .

[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

Import this dll file for getting the command line window on the foreground. Then I modified the Close button event like this.

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{   
    Process proc = Process.GetProcessById(pid);
    IntPtr h = proc.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("^(C)");          
}

Call process.Kill(); method , that will stop the associated process.

Depends on whether you're showing a window or not. If you are showing a window use:

process.CloseMainWindow();

If you're not, you can search for the process name and close it:

System.Diagnostics.Process.GetProcessesByName("Process Name").First().Kill();
System.Diagnostics.Process.GetProcessesByName("Process Name").First().Close();

For better results try to put the previous code in a try-catch bloc

Add this line to the constructor of Form:

Application.ApplicationExit += (s, ev) => process.Kill();

EDIT

Use this code:

if (process.MainWindowHandle != IntPtr.Zero)
    process.CloseMainWindow(); // this Closes process by sending a close message to its main window.
else
    process.Kill(); // this kills Hidden window
process.Close(); // Frees all resources that are associated with process.

handle the application exit event and close the process in this event handler.

public static event EventHandler ApplicationExit

example:

// Attache Handler to the ApplicationExit event.
Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

Handler:

private void OnApplicationExit(object sender, EventArgs e) {

    try {
        // Ignore any errors that might occur while closing the file handle.
        process.Kill();
    } 
    catch {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM