避免用户关闭7za.exe程序,直到进程完成

时间:2016-07-28 17:22:55

标签: c# zip formclosing

有一种方法可以阻止用户在进程中关闭7za.exe窗口吗?我需要显示文件夹提取的进度,但如果用户关闭窗口,这可能会导致我的C#程序出现一些错误。

public partial class ExtractForm : Form
{
    public ExtractForm()
    {
        InitializeComponent();
    }

    private void ExtractForm_Load(object sender, EventArgs e)
    {
        InitializeEvent();
    }

    private void InitializeEvent()
    {
        Zip.LogFileExtract +=WriteExtractProgression;
    }

    private void WriteExtractProgression(string text)
    {
        if (InvokeRequired)
        {
            this.BeginInvoke(new Action<string>(WriteExtractProgression), text);
        }
        else
        {
            txtExtract.Text += text;
            txtExtract.SelectionStart = txtExtract.TextLength;
            txtExtract.ScrollToCaret();
            txtExtract.Refresh();
        }
    }
}

处理方法:

ExtractForm extractForm = new ExtractForm();
extractForm.Show();

Process zipProcess = new Process();
        using (zipProcess)
        {
            zipProcess.StartInfo.UseShellExecute = false;            //Show the cmd.
            zipProcess.StartInfo.RedirectStandardOutput = true;
            zipProcess.OutputDataReceived += (object sender, DataReceivedEventArgs outline) =>
            {
                LogFileExtract(outline.Data);
                // Add args to a TextBox, ListBox, or other UI element
            };
            zipProcess.StartInfo.CreateNoWindow = true;
            zipProcess.StartInfo.FileName = pathToZip;
            zipProcess.StartInfo.Arguments = args;
            zipProcess.Start();
            zipProcess.BeginOutputReadLine();
            zipProcess.WaitForExit();    //Wait the process to finish completely.

        }
        extractForm.Close();
    } 

1 个答案:

答案 0 :(得分:1)

即使您启动了外部窗口,也无法直接阻止关闭外部窗口。

对于此特定用例,您可以使用以下内容捕获您开始的Process的输出:

process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => 
{
    // Add args to a TextBox, ListBox, or other UI element
}
process.Start();
process.BeginOutputReadLine();

这将使您可以直接控制UI元素。作为奖励,控制台窗口在运行时不会丢失在应用程序后面。