Touseef Khan
Touseef Khan

Reputation: 443

How to stop window form to reopen on click using C#?

I am using MDIParent window form which contains menus, when I click on same menu again it open a new window. so how to stop this from reopening the window if it is already open? It should not display window form every time on click.

Upvotes: 0

Views: 1904

Answers (4)

Akram Shahda
Akram Shahda

Reputation: 14781

Use Application.OpenForms property.

Boolean found = 
   Application.OpenForms.Cast<Form>().Any(form => form.ID == "TargetFormID"

if (!found) 
{ 
    // Open a new instance of the form //
}

Upvotes: 2

Bobby
Bobby

Reputation: 11576

Another why would be to create a Property in the Form which keeps the default instance you use.

private static Form _defaultInstance;
public static Form DefaultInstance()
{
    get {
        if(_defaultInstance == null || _defaultInstance.IsDisposed)
        {
            _defaultInstance = new yourTypeHere();
        }

        return _defaultInstance;
    }
}

And now you always access your window through this property:

yourTypeHere.DefaultInstance.Show();

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49261

2 ways:

Way 1, flags:
Keep a flag (or list of flags) for the open forms.
Each time you open the form (create a new() one) set the flag to "true".
When the form closes, set the flag to false.
In the button's click event, check the flag to see if the form is open before creating a new one.

Way 2, keep a reference:
Keep a reference in the main form to all the forms you're using.
Initialize them as null when the forms aren't open.
When you open a new form set the reference to it.
On the button's click event check if the form's reference is null before you create a new one.

I prefer the second way. It's easier to control your resources when you have references to all your sub-forms.

Upvotes: 1

Jonathan
Jonathan

Reputation: 12015

You could maintain a list of open forms (and check the list in the onClick event), or disable/enable the menu item when the form opened ot closed.

Upvotes: 0

Related Questions