同时打开两个表格

Open two forms at the same time

我找到了一个很棒的解决方案,但它是为在应用程序启动时工作而编写的,我想通过单击按钮来完成。它有效,但也使主窗体也处于活动状态,现在我可以根据需要多次打开这两个窗体。好吧,这不是一个理想的功能。如何在两个窗体处于活动状态时锁定主窗体?另外,我们添加了 ESC 键来关闭表单。单独打开表单时ESC有效,现在同时打开两个表单我们可以整天按ESC而不会做任何事情。

下面是我使用的代码:

public class MultiFormContext : ApplicationContext
{
    private int openForms;
    public MultiFormContext(params Form[] forms)
    {
        openForms = forms.Length;

        foreach (var form in forms)
        {
            form.FormClosed += (s, args) =>
            {
                //When we have closed the last of the "starting" forms, 
                //end the program.
                if (Interlocked.Decrement(ref openForms) == 0)
                    ExitThread();
            };

            form.Show();
        }
    }
}

然后我从主窗体创建了两个窗体,如下所示:

private void simpleButton1_Click(object sender, EventArgs e)
    {
        Cursor = Cursors.WaitCursor;
        using (new MultiFormContext(new fmUgyek(), new fmNaptar()))
        Cursor = Cursors.Default;
    }

提前感谢您的帮助!

您可以尝试这样的操作:

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    Form3 frm3 = null;

    frm2.Shown += (s, args) =>
    {
        frm3 = new Form3();
        frm3.Show();
    };

    frm2.FormClosing += (s, args) =>
    {
        frm3.Close();
    };

    frm2.ShowDialog(this);
}

Form2 使用 ShowDialog 显示,这将阻止 Form1 被选中。当显示 Form2 时,它会在其 Shown 事件中显示 Form3。如果 Form2 关闭,它也会关闭 Form3