显示“请稍候”消息框

时间:2012-09-20 03:37:33

标签: c# winforms

我希望在主要表单执行冗长的任务时显示“请稍候”消息框。至于我的情况,冗长的任务是传输串行协议。以下是我的代码:

public void transmitprotocol()
{    
    try
    {
         MessageBox.Show("Please wait. Uploading logo.", "Status");

         // Transmitting protocol coding here. Takes around 2 minutes to finish.

    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }
}

我已经尝试过使用MessageBox的上述方法,就像上面的编码一样,但我总是要关闭MessageBox才会开始传输协议。 我有什么方法可以在传输协议时仍然显示“请等待”MessageBox吗?

3 个答案:

答案 0 :(得分:9)

您需要在后台线程上执行昂贵的操作。为此,使用BackgroundWorker或新的并行化库(.NET 4等)。

实际上你需要关闭对话框,因为它会阻止执行,直到你关闭它为止。你所做的是你开始操作,然后显示对话框,然后,一旦操作完成,你关闭对话框。

现在,如果您正在使用WPF,我强烈建议您不要使用对话框,而是使用Busy Indicator,它是免费的,非常易于使用,并且不像消息框那么难看。

编辑:既然你指定你正在使用WinForms,那么继续,实现背景工作,为什么不,一个没有chrome的透明窗口,其目的是显示忙碌标签。一旦后台工作人员结束,你关闭那个窗口。

enter image description here

答案 1 :(得分:4)

您必须准备一个后台工作者并使用Windows窗体而不是MessageBox。 像这样简单的复制/粘贴:

    Form1 msgForm;
    public void transmitprotocol()
    {
        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        //you can use progresschange in order change waiting message while background working
        msgForm = new Form1();//set lable and your waiting text in this form
        try
        {
            bw.RunWorkerAsync();//this will run all Transmitting protocol coding at background thread

            //MessageBox.Show("Please wait. Uploading logo.", "Status");
            msgForm.ShowDialog();//use controlable form instead of poor MessageBox
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        // Transmitting protocol coding here. Takes around 2 minutes to finish. 
        //you have to write down your Transmitting codes here
        ...

        //The following code is just for loading time simulation and you can remove it later. 
        System.Threading.Thread.Sleep(5*1000); //this code take 5 seconds to be passed
    }
    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //all background work has complete and we are going to close the waiting message
        msgForm.Close();
    }

答案 2 :(得分:0)

最简单的方法是使用show()打开启动画面 打开所需的表单并在构造函数中传递一个splash表单实例:

        Wait myWaitDialog = new Wait(); //Wait is your splash
        myWaitDialog.Show();
        myWaitDialog.Refresh(); //Otherwise screen fails to refresh splash
        ScheduleClassForm myForm = new ScheduleClassForm(myWaitDialog);
        myForm.TopLevel = true;
        myForm.ShowDialog();

将此代码添加到生成的表单构造函数中:

    public ScheduleClassForm(Form WaitWindow)
    {            
       InitializeComponent();
       WaitWindow.Close();
    }

对我来说,它在form_load中失败但在构造函数中工作。关闭WaitWindow之前,请确保您的工作已完成(例如数据库加载)。

相关问题