Thursday, January 14, 2010

How to check if an application is already running - cppbuilder

A great little function that is used to check if an application is already running. Change the mutex string to an unique value for each application that requires it.

C++ Code:
//---------------------------------------------------------------------------
// Function: CheckDuplicate
// Reason: To check if an application is already running.
// Usage:
// bool running = CheckDuplicate();
// if (running)
// {
// ShowMessage("You cannot run two instances of this application");
// this->Close();
// }
//---------------------------------------------------------------------------
bool CheckDuplicate()
{
/* Change the ABCDEF-0123456789 value to a random string */
HANDLE hMutex = ::CreateMutex(NULL, FALSE, "ABCDEF-0123456789");
bool isRunning = (GetLastError() == ERROR_ALREADY_EXISTS);
if (hMutex) ::ReleaseMutex(hMutex);
return isRunning;
}
//---------------------------------------------------------------------------

Example of usage (cppbuilder project):
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------------
bool CheckDuplicate();
//---------------------------------------------------------------------------
USEFORM("Unit1.cpp", Form1);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
// Don't run if we're already running
if (CheckDuplicate()) return -1;
Application->Initialize();
Application->Title = "My App";
Application->CreateForm(__classid(TForm1), &Form1);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
return 0;
}
//---------------------------------------------------------------------------
bool CheckDuplicate()
{
HANDLE hMutex = ::CreateMutex(NULL, FALSE, "MY-APPLICATION-1234");
bool isRunning = (GetLastError() == ERROR_ALREADY_EXISTS);
if (hMutex) ::ReleaseMutex(hMutex);
return isRunning;
}
//---------------------------------------------------------------------------

You can download a complete project example (built with Borland C++ Builder 6) here.