VC++ 只執行一個程式例項
原始碼如下:
#pragma once
#define DECLARE_SinglePrj SinglePrj* SinglePrj::m_pSinglePrj = NULL;
#define SinglePrj_InitInstance(szPropName) SinglePrj *pSinglePrj = SinglePrj::GetInstance();\
if (NULL != pSinglePrj)\
if(!pSinglePrj->InitInstance(szPropName)) return FALSE;
#define SinglePrj_OnInitDialog SinglePrj *pSinglePrj = SinglePrj::GetInstance(); \
if (NULL != pSinglePrj) pSinglePrj->OnInitDialog(m_hWnd);
class SinglePrj
{
public:
static SinglePrj *m_pSinglePrj;
static SinglePrj *GetInstance()
{
if (NULL == m_pSinglePrj) m_pSinglePrj = new SinglePrj();
return m_pSinglePrj;
}
bool InitInstance(CString szPropName)
{
m_szPropName = szPropName;
m_hValue = (HANDLE)1;
HWND oldHWnd = NULL;
EnumWindows(EnumWndProc,(LPARAM)&oldHWnd);
if (NULL == oldHWnd) return true;
::ShowWindow(oldHWnd,SW_SHOW);
::SetForegroundWindow(oldHWnd);
return false;
}
void OnInitDialog(HWND hwnd)
{
SetProp(hwnd,m_szPropName,m_hValue);
}
private:
static BOOL CALLBACK EnumWndProc(HWND hwnd,LPARAM lParam)
{
SinglePrj * pSinglePrj = GetInstance();
if (NULL == pSinglePrj) return false;
HANDLE h = GetProp(hwnd,pSinglePrj->m_szPropName);
if( h == pSinglePrj->m_hValue)
{
*(HWND*)lParam = hwnd;
return false;
}
return true;
}
private:
SinglePrj(){}
CString m_szPropName;
HANDLE
m_hValue;
};
使用方法:
以程式名為 _T("Test") 為例
1.任意cpp中宣告巨集
DECLARE_SinglePrj
2.程式初始化函式中宣告巨集:
SinglePrj_InitInstance( _T("Test") )
2.窗體初始化函式中宣告巨集:
SinglePrj_OnInitDialog