Home / Learn programming language / How To Prevent Duplicate Winforms in c#

How To Prevent Duplicate Winforms in c#

This article is based on how to check if a form is already open in C# or as some calls it how to open only one instance child form in c#. This has a lot of advantage especially to a real world application. Knowing how to open only one child form at a time in c# will help save you from redeclaring your variables which may cause a whole lot of issues for you. Keeping one form instance is a good practice in desktop app development. So let see how to prevent duplicate winforms in c#

private void changePassMenu_Click(object sender, EventArgs e)

{

foreach (Form f in Application.OpenForms)

{

if (f is ChangePass)

{

f.Focus();

return;

}

}

new ChangePass().Show();

}

For each is the looping thing in c#. It loops through all the forms already open in your application and check for the name equivalency and if it matches then it brings the form to the frontpage i.e. it focus on the form and if the form isn’t opening then it opens a new instance of it. And if you have anything to do with your open form then get more properties from your f.

If you have any question please do contact me. Thanks for reading.

data-matched-content-rows-num="2" data-matched-content-columns-num="2" data-matched-content-ui-type="image_stacked"

About Joseph Sam

Check Also

c# access database

How to Send email using c#

Emailing can be something very essential to some application maybe your client might be in …

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »