C# How to find out if a form is running

Ismael Oliveira 1 Reputation point
2020-09-17T01:00:21.713+00:00

Hi, folks.
I have a form application in C# (I use Visual Studio) that has two items in a menu. Both of them show the same form, but with different data. They access different tables in the database. If the user clicks in one of the menu items, the form is shown. After that, if the user clicks in the other menu item, the app should show the other data in a different instance of the form. If the user clicks on the same menu item, the app should ony focus that form already open. How can I know which instante of the form was triggered?
Can anyone help me?
Thanks.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,869 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 114.5K Reputation points
    2020-09-17T05:16:21.507+00:00

    Add two members and handle the menu commands in this manner:

    Form2 form2A = null;
    Form2 form2B = null;
    
    private void menuAToolStripMenuItem_Click( object sender, EventArgs e )
    {
     if( form2A == null )
     {
     form2A = new Form2( );
     // load data from first table...
     form2A.Show( );
     }
    
     form2A.Activate( );
    }
    
    private void menuBToolStripMenuItem_Click( object sender, EventArgs e )
    {
     if( form2B == null )
     {
     form2B = new Form2( );
     // load data from second table...
     form2B.Show( );
     }
    
     form2B.Activate( );
    }
    

    The code is similar; therefore it can be combined into some common function.

    Probably can be done in case of MDI forms too.

    0 comments No comments

  2. Ismael Oliveira 1 Reputation point
    2020-09-19T22:09:16.287+00:00

    Ok, Viorel-1. I'll try. Thanks