Wednesday, October 14, 2009

Single Instance Application in C#

Hello Friends,

Today I am discussing here a very HOT topic i.e. Single Instance in C#.

So friends, There are lots of ways to do so.
Some are very easy as 2-3 lines of code, some are big and complicated.
Just go through all of them.

Methods.
  1. Using Process Name, ID etc.
  2. By using Mutex class
  3. By using Microsoft.VisualBasic.dll
  4. By locking or binding a file.
  5. By locking a particular port.
First Method:- Using Process class

Step1. Give your window form a specific unique name.

this.Text = “My_Application_144”; // title name

Step2. Create a private method for checking all Process title Text.

private bool IsAnotherInstance()
 {
    foreach (Process process in Process.GetProcesses())
     {
        //give particular name same as you given above
        if (process.MainWindowTitle == this.Text) 
           return false;
     }
    return true;
 }

Step3. On form load method check another instance

if (!IsAnotherInstance ())
 {
     MessageBox.Show("Application is Already running.");
     this.Close();
 }

I will disscuss other method next time.
==================================================
2. Using Mutex Class

  
   [STAThread]
   static void Main()
   {
     bool isNew = true;
     using (Mutex mutex = new Mutex(true, "MyApplicationName", out isNew))
     {
       if (isNew)
       {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new Form1());
       }
       else
       {
          MessageBox.Show("Already running");
       }
     }
   }

No comments:

Post a Comment