pBook‎ > ‎Only One Instance C++‎ > ‎

Run Only One Instance C++

posted Oct 19, 2015, 4:53 AM by Javad Taghia   [ updated Oct 19, 2015, 4:59 AM ]
CLimitSingleInstance g_SingleInstanceObj(TEXT("Global\\{9DA0BEED-7248-450a-B27C-C0409BDC377D}"));
int main(int argc, char *argv[])
{
if (g_SingleInstanceObj.IsAnotherInstanceRunning())
       return 0;

Add the above to your main file and add the following header file to your project. The text given in 9DA0BEED-7248-450a-B27C-C0409BDC377D should be unique for the program you run.

You can use the name of the program for example and remove the Global if you don't need for every user.

CLimitSingleInstance g_SingleInstanceObj(TEXT("HLController"));
int main(int argc, char *argv[])
{
if (g_SingleInstanceObj.IsAnotherInstanceRunning())
       return 0;


#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H

#include <windows.h> 

//This code is from Q243953 in case you lose the article and wonder
//where this code came from.
class CLimitSingleInstance
{
protected:
  DWORD  m_dwLastError;
  HANDLE m_hMutex;

public:
  CLimitSingleInstance(TCHAR *strMutexName)
  {
    //Make sure that you use a name that is unique for this application otherwise
    //two apps may think they are the same if they are using same name for
    //3rd parm to CreateMutex
    m_hMutex = CreateMutex(NULL, FALSE, strMutexName); //do early
    m_dwLastError = GetLastError(); //save for use later...
  }
   
  ~CLimitSingleInstance() 
  {
    if (m_hMutex)  //Do not forget to close handles.
    {
       CloseHandle(m_hMutex); //Do as late as possible.
       m_hMutex = NULL; //Good habit to be in.
    }
  }

  BOOL IsAnotherInstanceRunning() 
  {
    return (ERROR_ALREADY_EXISTS == m_dwLastError);
  }
};
#endif
ċ
LimitSingleInstance.h
(1k)
Javad Taghia,
Oct 19, 2015, 4:53 AM
Comments