How to limit 32-bit applications to one instance in Visual C++ (with or without Qt)

Posted on Posted in Qt Tutorials, Tutorials

I use the code from the following article to allow only a single instance of my programs (mostly written using Qt Framework) to run on Windows. Some programs (specially the ones which connect to a specific type of hardware or resource) need this limitation to avoid conflicts.

Please also note that this code is specific to Windows.

#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
  DWORD  m_dwLastError;
  HANDLE m_hMutex;

  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...
    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);

Leave a Reply

Your email address will not be published. Required fields are marked *