开发者

detecting an open form

I am opening a Form2 on a button click within Form1: Form2 f2 = new Form2()

In the case when the Form2 is already open, clicking the button on Form1 again shows that Form2 which is already open. But i want that the Form2 should not open when it is already open.

When Form2 is closed, then on clicking on the button again, it should display the Form2(as the Form2开发者_如何学Go is closed i.e. no instance of it is running).

How can this be done?

EDIT: I want that the Form2 should not open when it is already open.


You can also use the Application.OpenForms property to return a collection of all open windows forms. You can search through this collection to see if a Form1 (or a Form2) is currently open.


In addition to SLaks answer, check form.IsDisposed also, so that you have

void Something() {
    if (form == null || form.IsDisposed)
        form = new OtherForm();
    form.Show();
}

Also I find form.Activate() helpfull so that you get focus in form


You need to make a field in the first form that holds the existing instance of the second form.

For example:

OtherForm form;

void Something() {
    if (form == null)
        form = new OtherForm();
    form.Show();
}


  • Show the form after creation,
  • Activate the form to bring it to the front (or flash the window caption, if your app was in the background). This requires that the form Visible property is set to true, but this is the default in Visual Studio.

    private void ShowForm1(object sender, EventArgs e)
    {
        if (this.form1 == null)
        {
            this.form1 = new Form1();
            this.form1.Show(); 
        }
        else
        {
            this.form1.Activate();
        }
    }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜