首页 > 解决方案 > 跟随 c# 中的外部进程并显示消息

问题描述

复习答案,我会在启动 process.start() 时更详细;在任务管理器中会生成一个名为 ffmpeg.exe 的进程,这是执行剪切并将其保留在网络文件夹中的进程。我需要显示一个 messagebox.show (最后剪掉);指示继续生成不同剪辑的人可以查看完成的剪辑

                System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = $@"/k ffmpeg.exe {arguments}";
           
            process.StartInfo = startInfo;
            process.Start();

此 ffmpeg.exe 进程已创建

在此处输入图像描述

然后它在剪切成功完成后从任务管理器中消失,我想显示一个 messagebox.show(); 表示被剪掉了审查

标签: c#winforms

解决方案


您可以在开始该过程后立即添加此代码:

            process.WaitForExit();

然后,您的应用程序将等待 FFmpeg 的任务完成。

** 更新:为了防止应用程序被冻结,您有 2 个选项。

  1. 您可以在单独的线程中运行进程启动器:

          bool taskFinished=false;   //define a boolean to use that for checking if the process finished.
         new Task(() =>
         {
         System.Diagnostics.Process process = new System.Diagnostics.Process();
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
         startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         startInfo.FileName = "cmd.exe";
         startInfo.Arguments = $@"/k ffmpeg.exe {arguments}";
    
         process.StartInfo = startInfo;
         process.Start();
         process.WaitForExit();       
         taskFinished=true;     
         }).Start();
    

请注意,如果您想在上述单独的任务中运行进程,即使进程正在运行,应用程序也会转到下一行。为了管理这一点,您需要定义一个布尔值来使用它来检查进程是否完成。

  1. 您可以使用事件来检查进程是否结束。代码将是这样的:

         System.Diagnostics.Process process = new System.Diagnostics.Process();
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
         startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         startInfo.FileName = "cmd.exe";
         startInfo.Arguments = $@"/k ffmpeg.exe {arguments}";
    
         process.StartInfo = startInfo;
         process.EnableRaisingEvents = true; //add this
         process.Exited += new EventHandler(ProcessExited); //define an event that will be triggered after process get exited.
    
         process.Start();
    
         void ProcessExited(object sender, System.EventArgs e)
         {
         // Write the codes that you want to get executed after the process is finished/exited.
         }
    

推荐阅读