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 t开发者_运维知识库his from reopening the window if it is already open? It should not display window form every time on click.
Use Application.OpenForms property.
Boolean found =
Application.OpenForms.Cast<Form>().Any(form => form.ID == "TargetFormID"
if (!found)
{
// Open a new instance of the form //
}
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.
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.
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();
精彩评论