How to limit single instance of an application

13 10 2009

Description

 

 

Some applications are built to allow users to run single instance of an application at a time. That means we need to get an information from first instance of an application to the second instance and thus we need to prevent the second instance from running.

HowCanIDoIt1

 

 

We can use one of the synchronization objects mutex to ensure two or more threads do not attempt to access a shared memory simultaneously. We need to check it within the startup(WinMain) of the application.

MyCodeSnippet

BOOL WinMain()
{
if(!IsInstanceRunningAlready)
{
return FALSE;
}
//Do further operations
return FALSE;
}
BOOL IsInstanceRunningAlready()
{
// For handling Single Instance of Application
HANDLE hSingleInstance = NULL;
hSingleInstance = CreateMutex( NULL, FALSE,_T(“ApplicationName”));
DWORD dwLastError = GetLastError();
if(dwLastError == ERROR_ALREADY_EXISTS)
{
AfxMessageBox(_T(“Application already running”));
CloseHandle(hSingleInstance);
return 0;
}
return 1;

 

 

BOOL WinMain()
{
   if(!IsInstanceRunningAlready)
   {
      return FALSE;
   }

   //Do further operations here

   return FALSE;
}

BOOL IsInstanceRunningAlready()
{
   // For handling Single Instance of Application
   HANDLE hSingleInstance = NULL;
   hSingleInstance		= CreateMutex( NULL, FALSE,_T("ApplicationName"));
   DWORD dwLastError	= GetLastError();

   if(dwLastError == ERROR_ALREADY_EXISTS)
   {
      AfxMessageBox(_T("Application already running"));
      CloseHandle(hSingleInstance);
      return 0;
   }

   return 1;
}
Advertisements

Actions

Information

One response

26 11 2013

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: