Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

How to avoid multiple instances of your Windows application

4.90/5 (9 votes)
27 Sep 2010CPOL1 min read 30.1K  
I want to share a simple class I use for this purpose. The class operates on kernel objects.
I have seen this question asked quite a bit with different solutions provided. The ones involving registered window handles or registered messages seem very tedious and code bloat. I use something else that I find to be very simple and I want to share it. It involves a few set of functions, that operate on a kernel object, that I have rolled into a simple reusable class.

I searched and I didn't come across what I use. May be it isn't published. Anyway, it isn't a radically new idea.


Kernel objects are things that can be shared across different applications, and hence multiple instances of one application. The basic idea involves the very first instance of the application creating a kernel object and the others checking for it's existence and when found taking suitable actions.

There are several kinds of kernel objects available but the simplest one that has a very low overhead on the system resources is an event object. This is the one used for thread synchronization but here it serves a different purpose.

The following code is all that it takes.

#include <windows.h>
class SingleInstanceGuard
{
public:
	SingleInstanceGuard(const char *pID):m_pid(pID), m_h(NULL){}
	~SingleInstanceGuard(){CloseHandle(m_h);}
	bool AlreadyRunning()
	{
		if(m_h = OpenEvent(EVENT_ALL_ACCESS, FALSE, m_pid)) 
 		    return true;
		m_h = CreateEvent(NULL, FALSE, FALSE, m_pid);
		return false;
	}
private:
	const char *m_pid;
	HANDLE m_h;
};


The function AlreadyRunning() can be implemented in another way too, as follows

bool AlreadyRunning()
{
    m_h = CreateEvent(NULL, FALSE, FALSE, m_pid);
    return ERROR_ALREADY_EXISTS == GetLastError();
}


The code listed below demonstrates the usage.

#define TAG "QWERTY-12345"

void main()
{	
	SingleInstanceGuard sig(TAG);
	if(sig.AlreadyRunning()) return;
	MessageBox(NULL, "I am the only one of my kind", "Look", 0);
}


You may look up MSDN or the web for more details on the terms involved if you aren't familiar with them already.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)