How-To: Limit an application to one instance in C++

October 26th, 2009 Leave a Comment

There are many times when we want to limit our application to running only one instance at any one time, for example, a client chatting application, BitTorrent application, patcher application and the list goes on. However, there isn’t any quick-click available in the compilers out there. This means we need to write code to handle the problem.

In order to limit an application to one instance, regardless if it is a Windows application or console application, we need to use a named mutex that can be checked across all processes. Mutex (aka mutual exclusion) algorithm is known to prevent simultaneous use of a non-sharable resources. Hence, we are going to make use of mutex algorithm to limit our application to one instance only.

Here is the class for creating the instance-limiting named mutex.

#ifndef __LimitSingleInstance_h__
#define __LimitSingleInstance_h__

#include <Windows.h>

class LimitSingleInstance
{
public:
    LimitSingleInstance(const char * pMutexName)
    {
        // Create a named mutex.
        m_hMutex = CreateMutex(NULL, FALSE, pMutexName);
        // Store the error for later used.
        m_bAlreadyExists = (ERROR_ALREADY_EXISTS == GetLastError());
    }   // LimitSingleInstance

    ~LimitSingleInstance()
    {
        if(m_hMutex != NULL)
        {
            CloseHandle(m_hMutex);
        }
    }   // ~LimitSingleInstance

    BOOL IsAnotherInstanceRunning()
    {
        return m_bAlreadyExists;
    }   // IsAnotherInstanceRunning

private:
    BOOL m_bAlreadyExists;

};  // class LimitSingleInstance

#endif

Next, we will use the class to limit our application.

If you are writing a console application, it can be used in this form.

#include "LimitSingleInstance.h"

// This unique string is generated from GUID.
LimitSingleInstance g_Instance("{45640430-19E1-48cf-B658-0ADDC33BBD3F}");

int main(int argc, char * argv[])
{
    if(g_Instance.IsAnotherInstanceRunning())
    {
        return -1;
    }

    // Rest of the code
    // ...
}   // main

For a Windows application, it will look something like this.

#include "LimitSingleInstance.h"

LimitSingleInstance g_Instance("{45640430-19E1-48cf-B658-0ADDC33BBD3F}");

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int iCmdShow)
{
    if(g_Instance.IsAnotherInstanceRunning())
    {
        return -1;
    }

    // Rest of the code
    // ...
}   // WinMain

To generate the unique string (if you don’t already have one), you can use Visual Studio’s Create GUID (Globally Unique Identifier). It is found in Tools -> Create GUID.


Official MSDN website
http://msdn.microsoft.com/en-us/default.aspx

Tags:
, , ,

Leave a Reply


+ one = 3