打开第二个WinForm的异步但仍表现为孩子父窗体? [英] Open a second winform asynchronously but still behave as a child to the parent form?

查看:134
本文介绍了打开第二个WinForm的异步但仍表现为孩子父窗体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个应用程序,我想实现当一个漫长的过程正在发生时出现的进度窗口。

I am creating an application and I would like to implement a progress window that appears when a lengthy process is taking place.

我已经创建了一个标准的windows窗体项目我已经创建使用默认的形式我的应用程序。我还创建了一个新的形式,进度窗口中使用

I've created a standard windows form project to which I've created my app using the default form. I've also created a new form to use as a progress window.

当我打开进度窗口(在一个函数)的问题就出现了:

The problem arises when i open the progress window (in a function) using:

ProgressWindow.ShowDialog();

当遇到此命令,重点是进度窗口上,我认为它现在谁的窗口主循环正在处理的事件。 ,不足之处是它可以阻止我冗长的操作的主要形式执行

When this command is encountered, the focus is on the progress window and I assume it's now the window who's mainloop is being processed for events. The downside is it blocks the execution of my lengthy operation in the main form.

如果我打开使用进度窗口:

If I open the progress window using:

ProgressWindow.Show();



则窗口打开正确的,现在不堵的主要形式执行,但它不 ŧ充当孩子(模式)窗口应,即允许选择的主要形式,是不是集中在母公司,等等。

Then the window opens correctly and now doesn't block the execution of the main form but it doesn't act as a child (modal) window should, i.e. allows the main form to be selected, is not centered on the parent, etc..

任何想法如何,我可以打开一个新的窗口,但继续在主窗体处理?

Any ideas how I can open a new window but continue processing in the main form?

推荐答案

您可能是在一个单独的工作线程启动冗长的操作(如:使用后台工作)。然后使用显示表单的ShowDialog()和线程完成关闭你是显示该对话框。

You probably start your lengthy operation in a separate worker thread (e.g. using a background worker). Then show your form using ShowDialog() and on completion of the thread close the dialog you are showing.

下面是一个样本 - 在此笔者假设你有两种形式( Form1中窗体2 )。在 Form1中我从工具箱拉到的BackgroundWorker 。然后我连接的BackgroundWorker RunWorkerComplete 事件在我的窗体事件处理程序。下面是处理该事件,并显示在对话框中的代码:

Here is a sample - in this I assume that you have two forms (Form1 and Form2). On Form1 I pulled a BackgroundWorker from the Toolbox. Then I connected the RunWorkerComplete event of the BackgroundWorker to an event handler in my form. Here is the code that handles the events and shows the dialog:

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

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
        Thread.Sleep(5000);
        e.Result = e.Argument;
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
        var dlg = e.Result as Form2;
        if (dlg != null) {
            dlg.Close();
        }
    }

    private void button1_Click(object sender, EventArgs e) {
        var dlg = new Form2();
        this.backgroundWorker1.RunWorkerAsync(dlg);
        dlg.ShowDialog();
    }
}

这篇关于打开第二个WinForm的异步但仍表现为孩子父窗体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆