Click here to Skip to main content
16,019,273 members
Articles / Programming Languages / C#
Article

Checking for an existing instance of a Windows application, and setting the MDI parent form of an MDI child

Rate me:
Please Sign up or sign in to vote.
2.88/5 (8 votes)
8 Sep 2008CPOL2 min read 85.4K   18   21
How to check for an existing instance of a Windows application, and how to set the MDI parent form of an MDI child, how to list all MDI children, etc., in a C# Windows application.

Introduction

This article will describes two things:

  1. How to check for an existing instance of a C# Windows application.
  2. How to check whether a MDI child is set to an MDI parent, and if it is already loaded, then just activate it instead of creating a new instance and setting it as an MDI child.

The example code is written in C#. This article will especially help those who were VB 6.0 programmers and recently shifted to .NET.

Check for an existing instance of a Windows application

C#
using System.Diagnostics;

private static bool getPrevInstance()
{
    //get the name of current process, i,e the process 
    //name of this current application

    string currPrsName = Process.GetCurrentProcess().ProcessName;

    //Get the name of all processes having the 
    //same name as this process name 
    Process[] allProcessWithThisName 
                 = Process.GetProcessesByName(currPrsName);

    //if more than one process is running return true.
    //which means already previous instance of the application 
    //is running
    if (allProcessWithThisName.Length > 1)
    {
        MessageBox.Show("Already Running");
        return true; // Yes Previous Instance Exist
    }
    else
    {
        return false; //No Prev Instance Running
    }
}

Note: Instead of the above method of checking by process name, we can also use a mutex, but this method is easy compared to the mutex one, which requires a knowledge of threading. This method will work fine unless and until you change the process name for some specific reasons.

Alternate way using Mutex

C#
using System.Threading;
bool appNewInstance;

Mutex m = new Mutex(true, "ApplicationName", out appNewInstance);

if (!appNewInstance)
{
    // Already Once Instance Running
    MessageBox.Show("One Instance Of This App Allowed.");
    return;
}
GC.KeepAlive(m);

Check whether an MDI child is set to an MDI parent

The below code will check whether an MDI child is set to an MDI parent, and if it is already loaded, then just activate it instead of creating a new instance and setting it as an MDI child.

Suppose I have a Windows form named frmModule and I want to set it as an MDI child of an MDI form. I can call the function ActivateThisChill() with the name of the form as a parameter, to accomplish this:

C#
if (ActivateThisChild("frmModule") == false)
{
    frmModule newMDIChild = new frmModule();
    newMDIChild.Text = "Module";
    newMDIChild.MdiParent = this;
    newMDIChild.Show();
}
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipTitle = " Project Tracker Suite (PTS)";
notifyIcon1.BalloonTipText =  " PTS: Modules";
notifyIcon1.ShowBalloonTip(2000);


//This function will return true or false. 
//false means this form was not previously set 
//as mdi child hence needs to creat a instance
//and set it as a mdi child.


private Boolean ActivateThisChild(String formName)
{
    int i;
    Boolean formSetToMdi = false;
    for (i = 0; i < this.MdiChildren.Length; i++)
     // loop for all the mdi children
    {
        if (this.MdiChildren[i].Name == formName)
          // find the Mdi child with the same name as your form
        {
            // if found just activate it
            this.MdiChildren[i].Activate();
            formSetToMdi = true;
        }
    }

    if (i == 0 || formSetToMdi == false)
        // if the given form not found as mdi child return false.
        return false;

    else
        return true;


}

Note: The other way around is to use a static property in each form and check in your MDI parent whether the static property of that particular form is assigned a value or not, and then take actions accordingly.

Points of interest

My other articles of interest are:

  1. Using Crystal Reports with Oracle, and Parameterized Query (passing SQL query parameters to Crystal Reports)
  2. Attaching a digital certificate (public key) to an HTTPS SSL request

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Al-Jazirah Corporation Riyadh KSA
United Arab Emirates United Arab Emirates
I am a Software Engineer having 4 + years of experience in various skill sets.
Proficiency in Asp.net, C#.net, Vb.net, Ado.net, VB 6.0, J2ME, Ajax, Xslt, Xml, Smart Device (Pocket PC 2003), and Oracle.

Extensive experience with analyzing, designing, development, and maintenance of Internet, Intranet, Client Server and Object Oriented applications built on .NET Framework (windows and web app.) and VB 6.0.

Comments and Discussions

 
GeneralThanks Pin
TheMrJuano23-May-13 16:13
TheMrJuano23-May-13 16:13 
GeneralChecking for an instance of an MDI Child Pin
devrw21-Jan-09 6:01
devrw21-Jan-09 6:01 
GeneralInteresting topic! Pin
Aamer Alduais4-Sep-08 7:59
Aamer Alduais4-Sep-08 7:59 
GeneralRe: Interesting topic! Pin
Rehan Ahmad Abbasi6-Sep-08 0:23
Rehan Ahmad Abbasi6-Sep-08 0:23 
GeneralPlease Vote For this article [modified] Pin
Rehan Ahmad Abbasi24-Aug-08 2:57
Rehan Ahmad Abbasi24-Aug-08 2:57 
GeneralThis got me thinking Pin
Ilíon21-Aug-08 5:17
Ilíon21-Aug-08 5:17 
GeneralRe: This got me thinking [modified] Pin
Rehan Ahmad Abbasi22-Aug-08 23:43
Rehan Ahmad Abbasi22-Aug-08 23:43 
GeneralRe: This got me thinking Pin
Ilíon26-Aug-08 1:31
Ilíon26-Aug-08 1:31 
GeneralRe: This got me thinking Pin
Rehan Ahmad Abbasi26-Aug-08 3:19
Rehan Ahmad Abbasi26-Aug-08 3:19 
GeneralRe: This got me thinking [modified] Pin
Ilíon26-Aug-08 4:54
Ilíon26-Aug-08 4:54 
GeneralRe: This got me thinking Pin
Ilíon8-Oct-08 1:52
Ilíon8-Oct-08 1:52 
GeneralSetting the process name Pin
RichardDeZwart21-Aug-08 2:52
RichardDeZwart21-Aug-08 2:52 
GeneralRe: Setting the process name Pin
Rehan Ahmad Abbasi22-Aug-08 23:57
Rehan Ahmad Abbasi22-Aug-08 23:57 
GeneralRe: Setting the process name Pin
RichardDeZwart24-Aug-08 21:37
RichardDeZwart24-Aug-08 21:37 
GeneralRe: Setting the process name Pin
Rehan Ahmad Abbasi24-Aug-08 23:37
Rehan Ahmad Abbasi24-Aug-08 23:37 
GeneralRe: Setting the process name Pin
Ilíon26-Aug-08 1:52
Ilíon26-Aug-08 1:52 
GeneralRe: Setting the process name Pin
Rehan Ahmad Abbasi26-Aug-08 3:13
Rehan Ahmad Abbasi26-Aug-08 3:13 
GeneralRe: Setting the process name Pin
RichardDeZwart26-Aug-08 9:12
RichardDeZwart26-Aug-08 9:12 
GeneralRe: Setting the process name Pin
Ilíon8-Oct-08 1:49
Ilíon8-Oct-08 1:49 
Generaljust 1 flaw Pin
Xaroth20-Aug-08 9:33
Xaroth20-Aug-08 9:33 
if you change the process name, the check will fail and it'll allow multiple instances..

I suggest using a socket (works cross platform as well) or a Mutex (not sure if mono got this working properly already), they are more reliable as it's a program specific thing that cannot be easily changed.
GeneralRe: just 1 flaw Pin
Rehan Ahmad Abbasi20-Aug-08 21:37
Rehan Ahmad Abbasi20-Aug-08 21:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.