rulururu

post Single Instance managed by GUID

July 22nd, 2008

Filed under: C++ — Kai @ 3:29 pm

Some of the applications need to be restricted to run as a single instance. This can be achieved very easily in C++ applications.

When the application is started, it has to be checked if there is another instance running. If there is one already running, a message should be displayed and the application quit from the environment.

By default MFC provide no APIs or methods to satisfy this. But, by using mutex, the work is so simple.
For this we need a GUID (Globally Unique Identifier). You can create this by using the MFC application

A small tool called guidgen.exe generates a GUID.
First of all you have to start guidgen.exe. All you have to do is to click the New GUID button in the Create GUID dialog box.

After that you need to create a named mutex semaphore when you start your application. When the second one starts it tries to get access to the mutex but will fail…

Implement one method:

BOOL CThreadTestApp::SingleTest (LPSTR szName)
{
        HANDLE hMutex = CreateMutex (NULL, TRUE, szName);
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
           CloseHandle(hMutex);
           return FALSE;
        }
return TRUE;
}

Call the method in InitInstance() like:

if (SingleTest (_T("SingleTest_48C56927-A0DB-4e31-8C32-FE15FBA45043")))
{
 
}
else
{
   AfxMessageBox(_T("Error: application is already running!"));
   return FALSE;
}

This check is performed inside the CWinApp derived classes in MFC. The CWinApp::InitInstance function is the ideal place for performing such initial check-ups.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)