Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Win32 C/C++ Only one instance of an application is allowed to run, http://johnmhsheep.pixnet.net/blog, https://johnmhsieh.blogspot.com/
#include "SingleInstance.h"
//
CSingleInstance::CSingleInstance(TCHAR* pMutexName)
{
this->m_hMutex = CreateMutex(NULL, FALSE, pMutexName);
this->m_bExist = (ERROR_ALREADY_EXISTS == GetLastError())?TRUE:FALSE;
}
CSingleInstance::CSingleInstance(const CSingleInstance& instance)
{
if (this == &instance)
{
return;
}
//
// Do nothing
//
}
CSingleInstance& CSingleInstance::operator=(const CSingleInstance& instance)
{
//
// Do nothing
//
return *this;
}
CSingleInstance::~CSingleInstance()
{
if (this->m_hMutex != NULL)
{
CloseHandle(this->m_hMutex);
this->m_hMutex = NULL;
}
}
BOOL CSingleInstance::IsRunning(void)
{
return this->m_bExist;
}
#ifndef _SingleInstance_H_
#define _SingleInstance_H_
//
#include <Windows.h>
//
// Only one instance of an App is allowed to run.
// Usage: declare a global object, it doesn't work to declare a local.
// CSingleInstance si(L"MySingleInstance");
//
class CSingleInstance
{
public:
CSingleInstance(__in_opt TCHAR* pMutexName);
CSingleInstance(__in const CSingleInstance& instance);
CSingleInstance& operator=(__in const CSingleInstance& instance);
~CSingleInstance();
BOOL IsRunning(void);
private:
HANDLE m_hMutex;
BOOL m_bExist;
};
//
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment