C# - 等待进程退出和关闭“的ShowDialog()”

问题描述 投票:0回答:2

作为新的.NET,我不能够得到怎样关闭显示的对话框模式窗口,一旦它的开放。因为我已经学会了,我们不能自动关闭,直到明确其被调用。这里是我的代码:

//process - notepad.exe 
Process p = Process.Start(process); 
frm_Save fsave = new frm_Save(); 

Using (p)
{ 
    do
    { 
        if(!p.HasExited)    
        {
            p.Refresh();
            fsave.ShowDialog(); // it just stuck here and doesn't go to next line
        }
    } 
    while(!p.WaitForExit(1000)); 
}

//frm_Save.cs 
public frm_Save() 
{ 
    InitializeComponent(); 
}

private void frm_Save_Load(...,....)
{ 
    // 
}

private void frm_Save_Shown(...,...) 
{ 
    Sleep(100); 
    Forms.Application.DoEvents();
    Close(); 
}
c# modal-dialog task
2个回答
1
投票

正如你所解释的,要显示与图标要保存在后台的视频对话,并防止用户做一些事情。一个常规的方式来做到这一点是在你的Dialog BackgroundWorker。下面是它的代码是如何工作的:

public class frm_Save : Form
{
    public FrmProgress(List<TransferOptions> transferOptions)
    {
        InitializeComponent();
        BackgroundWorker BgrdWorker = new System.ComponentModel.BackgroundWorker();
        this.BgrdWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.BgrdWorker_DoWork);
        this.BgrdWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.BgrdWorker_RunWorkerCompleted);
    }

    private void FrmProgress_Load(object sender, EventArgs e)
    {
        // Show image and message...
    }

    private void BgrdWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        // Call your video Process start Function
        // after that
        var stopWatch = new StopWatch();
        stopWatch.Start()
        while (true)
        {
            if (stopWatch.ElapsedMilliseconds >1000 || videoProcessHasReturnedSuccessfully)
            {
                break
            }
        }
    }

    private void BgrdWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // inform the user the video processing is finished
        this.Close();
    }
}

然后,在当你要开始的整个过程您的控制台应用程序的主要形式,您拨打:

frm_Save fsave = new frm_Save(); 
fsave.ShowDialog()

提示:您还可以使用BgrdWorker.ProgressChanged由后台任务,并在必要的UI之间的通信,以显示后台任务给用户的进度,但你有没有要求你的问题。


1
投票

这种方法可以为你工作,注意使用最顶层的。

using System.Runtime.InteropServices; 

private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;   

[DllImport("user32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, 
  int X, int Y, int cx, int cy, uint uFlags);

....

frm_Save fsave = new frm_Save(); 
fsave.Show();

SetWindowPos(frm_Save.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

Process p = Process.Start(process); 

using (p)
{
    while (!p.WaitForExit(1000))
    {
        fsave.Refresh();
    }
}
fsave.Close();
© www.soinside.com 2019 - 2024. All rights reserved.