【问题标题】:Open two forms at the same time同时打开两个表格
【发布时间】:2017-06-23 13:27:33
【问题描述】:

我找到了一个很棒的解决方案,但它是为应用程序启动而编写的,我想通过单击按钮来完成。它可以工作,但也可以激活主表单,现在我可以根据需要多次打开这两个表单。好吧,这不是一个理想的功能。如何在两个表单处于活动状态时锁定主表单?还有一件事,我们添加了 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;
    }

提前感谢您的帮助!

【问题讨论】:

    标签: c# forms winforms applicationcontext


    【解决方案1】:

    你可以试试这样的:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2021-06-17
      • 2011-06-16
      相关资源
      最近更新 更多