Singleton Pattern is useful for creating just one instance of a class / object...
Try :
#pragma once
#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H
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
#pragma once
#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H
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
To copy to clipboard, switch view to plain text mode
In your main.cpp :
CLimitSingleInstance g_SingleInstanceObj(TEXT("Global\\{B5D47D64-F5F9-46e3-AFB8-EC34D0F863F1}"));
if (g_SingleInstanceObj.IsAnotherInstanceRunning())
{
"There is another instance of this application already running." );
return FALSE;
}
CLimitSingleInstance g_SingleInstanceObj(TEXT("Global\\{B5D47D64-F5F9-46e3-AFB8-EC34D0F863F1}"));
if (g_SingleInstanceObj.IsAnotherInstanceRunning())
{
QMessageBox::critical(NULL, "Warning",
"There is another instance of this application already running." );
return FALSE;
}
To copy to clipboard, switch view to plain text mode
Regards,
Steve
Bookmarks