#pragma once
// WAC.com Class Liblary for Visual C++
// Copyright (C) WAC.com Inc. All rights reserved.
//
// This file is a part of the WAC.com Class Liblary.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.TXT at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license. You must not remove this notice, or
// any other, from this software.
// '07.05.16 : コードの整備 (sha)
/////////////////////////////////////////////////////////////////////////////
// CSingleInstance
class CSingleInstance
{
public:
CSingleInstance()
{
m_hMutex = NULL;
}
CSingleInstance(LPCTSTR szUniqueName, bool bIsGlobal = false)
{
HRESULT hr = S_OK;
m_hMutex = NULL;
hr = this->Create(szUniqueName, bIsGlobal);
if (FAILED(hr))
{
// 無視する。。
}
}
virtual ~CSingleInstance()
{
this->Close();
}
public:
bool IsFirstInstance()
{
return (m_hMutex != NULL) ? true : false;
}
public:
HRESULT Create(LPCTSTR szUniqueName, bool bIsGlobal = false)
{
if (szUniqueName == NULL)
{
ATLASSERT(0);
return E_FAIL;
}
this->Close();
// システムグローバルな排他制御を行うか?
CString strUniqueName;
if (bIsGlobal)
{
strUniqueName.Format(_T("Global:%s"), szUniqueName);
}
else
{
strUniqueName = szUniqueName;
}
HANDLE hMutex = ::CreateMutex(NULL, FALSE, strUniqueName);
if (hMutex == NULL)
{
return E_FAIL;
}
DWORD dwResult = ::WaitForSingleObject(hMutex, 0);
switch(dwResult)
{
case WAIT_ABANDONED:
case WAIT_OBJECT_0:
m_hMutex = hMutex;
return S_OK;
break;
}
return E_FAIL;
}
void Close()
{
if (m_hMutex != NULL)
{
::ReleaseMutex(m_hMutex);
::CloseHandle(m_hMutex);
m_hMutex = NULL;
}
}
protected:
HANDLE m_hMutex;
};