Thursday, September 13, 2007

How to prevent a user from launching multiple instances of an application - .Net C# Code

Recently one of my friend asked me to solve a simple problem. How to prevent an end user from launching multiple instances of your application. Instantly it came to my mind - A Mutex(Very expensive resource though...) can be used and I digged some of my old work and here it is. So enjoy... this is far more better than going into processes list and validating your application is running or not?
using
System;
using
System.Windows.Forms ;
using System.Collections.Generic;

namespace

Skynet.Apps.NetBuddy
{
static class Program
{
/// <summary>
///
Define the Mutex
///
</summary>
private static System.Threading. Mutex PreviousInstance;

/// <summary>
///
The main entry point for the application.
///
</summary>
[STAThread
]
static void
Main()
{
Application
.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false
);
PreviousInstance = new System.Threading.Mutex(true , "NetBuddy");//Create a Mutex

if (PreviousInstance.WaitOne(0, false)) //Check for Existing Mutex
{
Application.EnableVisualStyles();
//Enable XP/Vista Visual Styles
Application.Run(new frmMain());
//Run Main Form
}
else
{
MessageBox .Show("You are trying to launch multiple Instance of NetBuddy." + Environment .NewLine + "This instance will terminate now.", "NetBuddy Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Warn User that another instance is running
}

}

}

}

No comments: