Avoiding multiple instance of a Windows Application

This code snippet allows you to restrict running multiple instances of an application. Put this in the main function of program.cs of your windows application.

This code needs System.Diagnostics namespace to be included in the Class.

Process aProcess = Process.GetCurrentProcess();
string aProcName = aProcess.ProcessName;

if (Process.GetProcessesByName(aProcName).Length > 1)
{
Application.ExitThread();
}

The most perfect method to avoid multiple instance running simultaneously is using the Mutex object of System.Threading class. Here is the sample,

bool isAlreadyRunning = false;
using (System.Threading.Mutex mtex = new System.Threading.Mutex(true, “MyApplication”, out isAlreadyRunning))
{
if (isAlreadyRunning)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmSplash());    //Startup form of your application
mtex.ReleaseMutex();
}
else
{
MessageBox.Show(“An application instance is already running.”, “MyApplication”,  MessageBoxButtons.OK);
}
}

put this code in the Main() function of Program.cs class of your windows application.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s