Skip to content

Instantly share code, notes, and snippets.

@johnhmj
Last active April 3, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnhmj/6803ee37a301363ca1c2dd9bc5236173 to your computer and use it in GitHub Desktop.
Save johnhmj/6803ee37a301363ca1c2dd9bc5236173 to your computer and use it in GitHub Desktop.
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