0

我有Form12 个单选按钮 (rb1rb2) 和一个普通按钮 ( btn)。当我单击时,btn我应该打开Form2,作为Form1if的 MDI childrb1被选中,或者作为普通Dialogifrb2被选中。而且,任何时候都只能Form2打开一个。

这是我的代码:

public partial class Form1 : Form
{

    Form2 f2;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (f2 != null) 
        {
            MessageBox.Show("Close form!");
            return;
        }

        f2 = new Form2();
        if (radioButton1.Checked == true)
        {
            this.IsMdiContainer = true;
            f2.MdiParent = this;
            f2.Show();
        }
        else
        {
            f2.Show();
        }

        f2.FormClosed += f2_FormClosed;

    }

    void f2_FormClosed(object sender, FormClosedEventArgs e)
    {
        this.IsMdiContainer = false;
        f2 = null;
    }

}

一切都按原样工作,除非我Form2作为 MDI 子最大化然后关闭它。之后屏幕保持不变(因为我什至没有关闭Form2)但我可以打开新Form2的,然后Form1的标题是“ Form1 - [Form2]”,如果我重复这个过程,它将是“ Form1 - [Form2] - [Form2]”,等等。

我发现我的f2_FormClosed方法应该是

    void f2_FormClosed(object sender, FormClosedEventArgs e)
    {
        f2.Hide(); // <<<<<<<<-----------NEW
        this.IsMdiContainer = false;
        f2 = null;
    }

但我不知道为什么;Form2应该关闭,我不知道我为什么要隐藏它?!

谢谢!

4

1 回答 1

0

I agree with Hans, switching IsMdiContainer at run-time is wonky and is likely to produce other side-effects you haven't seen yet.

Seriously consider a different design for your app.

With that in mind, here's probably the stupidest hack I'll post all day:

public partial class Form1 : Form
{

    Form2 f2;
    System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();

    public Form1()
    {
        InitializeComponent();
        tmr.Interval = 100;
        tmr.Enabled = false;
        tmr.Tick += delegate (object sender, EventArgs e) {
            tmr.Stop();
            this.IsMdiContainer = false;
        };
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (f2 != null)
        {
            MessageBox.Show("Close form!");
            return;
        }

        f2 = new Form2();
        f2.FormClosed += delegate(object sender2, FormClosedEventArgs e2) { 
            f2 = null; 
        };    
        if (radioButton1.Checked == true)
        {
            this.IsMdiContainer = true;
            f2.FormClosed += delegate(object sender3, FormClosedEventArgs e3) { 
                tmr.Start();
            };    
            f2.MdiParent = this;
        }
        f2.Show();
    }

}

*I originally tried Invoking the call to change IsMdiContainer but that didn't work, so I switched to the Timer. Stupidity that works. Use this solution with caution...

于 2015-02-06T17:15:05.753 回答