Saturday, November 10, 2007

Single Instance Application

Making an application single instance, can be achieved by using a mutex (Mutual Exclusion Semaphore). A Windows application loads the main form through the Application.Run( ) method. In the Main method, create a new mutex. If a new mutex is created the application is allowed to run. If the mutex has already been created, the application cannot start. This will ensure that only one instance will be running at any time.

// Used to check if we can create a new mutex
bool newMutexCreated = false;
// The name of the mutex is to be prefixed with Local\ to make
// sure that its is created in the per-session namespace,
// not in the global namespace.
string mutexName = "Local\\" +
 System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

Mutex mutex = null;
try
{
   // Create a new mutex object with a unique name
   mutex = new Mutex(false, mutexName, out newMutexCreated);
}
catch(Exception ex)
{
   MessageBox.Show (ex.Message+"\n\n"+ex.StackTrace+
        "\n\n"+"Application Exiting...","Exception thrown");
   Application.Exit ();
}

// When the mutex is created for the first time
// we run the program since it is the first instance.
if(newMutexCreated)
{
   Application.Run(new AnimatedWindowForm());
}

When a new mutex is created the mutex name can be prefixed with either Global\ or Local\. Prefixing with Global\ means the mutex is effective in the global namespace.

Prefixing with Local\ means the mutex is effective in the user's session namespace only.

Windows XP and Windows 2003 allow fast user switching through Terminal Services Sessions. So if a mutex is created with a Global\ prefix, the application can have only one instance system wide. So if one user launches the application, other users cannot create a second instance in their sessions. If the mutex is not prefixed with Local\ it is effective per session only.

No comments:

Post a Comment