程序对Process.Exited没有反应

问题描述 投票:-1回答:1

我正在尝试在WPF / C#应用程序中运行一些脚本(VBScript作为示例),并在脚本运行完成后使其自行关闭。

        string scriptName = "test.vbs";
        int abc = 2;
        string name = "Script";

        ProcessStartInfo ps = new ProcessStartInfo();
        ps.FileName = "cscript.exe";
        ps.Arguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", scriptName, abc, name);

        Process p = new Process();            
        p.StartInfo = ps;
        p.Exited += this.End;
        p.Start();
        p.Close();

我怎样才能做到这一点?事件“退出”就不会发生。

实际上没有p.EnableRaisingEvents = true是一个问题。正确的代码是:

        Process p = new Process();
        p.EnableRaisingEvents = true;
        p.StartInfo = ps;
        p.Exited += this.End;
        p.Start();
c# wpf vbscript
1个回答
2
投票

在等到完成之前关闭该过程。

在这种情况下,p.WaitForExit()似乎是等待进程完成的更好方法(只要您在进程运行时不想并行执行任何其他操作)。

using (Process p = new Process())
{
    p.StartInfo = ps;
    p.Start();
    p.WaitForExit();
    // Do whatever you want to do after the process has finished
}
© www.soinside.com 2019 - 2024. All rights reserved.