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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With