简体   繁体   English

在应用程序关闭时停止在 C# 中启动的命令行进程

[英]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,我已经在我的 C# 应用程序中的按钮单击事件上启动了一个过程,如下所示,

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.就像我在命令提示符中写命令一样,我通常按Ctrl + C停止执行。

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.我在网上找到了一个解决方案,SendKeys 但是我看不懂。 PS: It might be duplicate of some questions but some of them won't work for me. PS:这可能是一些问题的重复,但其中一些对我不起作用。

Thank you in Advance先感谢您

Thanks to @mjwills for guiding me. 感谢@mjwills指导我。

Later, I figured out that process.Start() in this case, started two different processes. 后来,我找出了那个process.Start()在这种情况下, process.Start()启动了两个不同的进程。 One is cmd.exe and another is node.exe . 一个是cmd.exe ,另一个是node.exe

process.Kill() only kill the cmd.exe . process.Kill()仅杀死cmd.exe So, I have figured it out that I have to find that node.exe process and kill it too. 因此,我发现必须找到该node.exe进程并将其杀死。

I have two solutions : 我有两种解决方案:

1. This might stop all the process named node.exe but for now, this worked for me. 1.这可能会停止所有名为node.exe的进程,但现在对我有用

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

2. As I mentioned in my question, Use SendKeys.SendWait("^(C)"); 2.正如我在问题中提到的,使用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. 导入该dll文件以使命令行窗口位于前台。 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(); 调用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为了获得更好的结果,尝试将之前的代码放在 try-catch 块中

Add this line to the constructor of Form: 将此行添加到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 {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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