单一实例

对话框项目

// APP 里面添加互斥量
class CvideoHelperApp : public CWinApp
{
...
private:
HANDLE m_hMutex;
...
}

BOOL CvideoHelperApp::InitInstance()
{
m_hMutex = CreateMutex(NULL, TRUE, _T("注册信息"));
if (NULL == m_hMutex)
{
return FALSE;
}
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
HWND hProgramWnd = ::FindWindow(NULL, _T("注册信息"));
if (hProgramWnd)
{
WINDOWPLACEMENT* pWndpl = NULL;
WINDOWPLACEMENT wpm;
pWndpl = &wpm;
GetWindowPlacement(hProgramWnd, &wpm);
if (pWndpl)
{
//将运行的程序窗口还原成正常状态
pWndpl->showCmd = SW_SHOWNORMAL;
::SetWindowPlacement(hProgramWnd, pWndpl);
SetWindowPos(hProgramWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
}
CloseHandle(m_hMutex);
m_hMutex = NULL;
return FALSE;
}
...
}

// 释放资源
int CvideoHelperApp::ExitInstance()
{
if (NULL != m_hMutex)
CloseHandle(m_hMutex);
m_hMutex = NULL;

return CWinApp::ExitInstance();
}

多文档项目

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs

cs.style |= WS_SYSMENU |WS_MINIMIZEBOX|WS_MAXIMIZEBOX;// | WS_VISIBLE | FWS_ADDTOTITLE | | WS_MINIMIZEBOX| WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MAXIMIZE;


// change mainframe's class name, so I can easily find it further.
LPTSTR APP_CLASSNAME = TEXT("ASLucky_SCHelper");
WNDCLASS wndCls;
HINSTANCE hInst = AfxGetInstanceHandle();

if(!(::GetClassInfo(hInst,APP_CLASSNAME,&wndCls)))
{
if(::GetClassInfo(hInst,cs.lpszClass,&wndCls))
{
wndCls.lpszClassName = APP_CLASSNAME;
wndCls.hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
if (!AfxRegisterClass(&wndCls))
AfxThrowResourceException();
}else
AfxThrowResourceException();
}
cs.lpszClass = APP_CLASSNAME;


return TRUE;
}


bool FirstInstance(TCHAR* pstrClass)
{
//CWnd* pwndFirst = CWnd::FindWindow((LPCTSTR)(DWORD_PTR)WC_DIALOG,strCaption);//for dialog
CWnd* pwndFirst = CWnd::FindWindow(pstrClass, NULL);
if (!pwndFirst)
{
return true;
}
// another instance is already running - activate it
CWnd* pwndPopup = pwndFirst->GetLastActivePopup();
pwndFirst->SetForegroundWindow();
if (pwndFirst->IsIconic())
pwndFirst->ShowWindow(SW_SHOWNORMAL);
if (pwndFirst != pwndPopup)
pwndPopup->SetForegroundWindow();
return false;
}

BOOL CEasyReminderApp::InitInstance()
{
if ( !FirstInstance(TEXT("ASLucky_EasyReminder")) )
{
return FALSE;
}
。。。
}