Forcing just one instance of an Application to execute at a time

By Akbar

When developing a desktop application, it’s often required that only one instance of application should be executable at a time. This is usually implemented in different ways depending on Language/Tools you are using to build the application.
Some common techniques used are either using the Mutex or getting a list of active processes and making sure that a process with same executable name is not already running. Here are the different articles which all discuss a bit different techniques to achieve the same goal:
http://dotnet.org.za/ernst/archive/2004/07/20/2887.aspx
http://www.codeproject.com/KB/cs/CSSIApp.aspx
http://www.ddj.com/windows/184416856
http://audiprimadhanty.wordpress.com/2008/06/30/ensuring-one-instance-of-application-running-at-one-time/

If you are developing your application in Visual C++, then there is a relatively simple and straight forward method. The trick is that you declare a shared segment for you executable and you set a variable in the shared data segment when the first instance of the application is run. When you try to run again the same application, it also shares the same data segment and thus you can check the value of the variable to see if another instance of application is running or not.
For this you can add the following code at top of your executable.

1
2
3
4
5
6
// This share data segment section is used to make sure that only instance of the application
// should be running at a time
#pragma data_seg(".singleInstance")
HWND g_hWnd = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:.singleInstance,rws")

Then you can check and set the g_hWnd in your Instance initialization method.

1
2
3
4
5
6
7
8
// Check if another instance of the application is already running
if (g_hWnd)
{
	// Post message to bring the main window to front
 
	// Another instance is already running, so quit.
	return false;
}

Don’t forget to assign the “g_hWnd” variable the reference of main window handle after you create that window. Credit for this technique goes to:
http://www.codeguru.com/cpp/misc/misc/applicationcontrol/article.php/c3763/

Tags: , , , ,