BOOL CSingleDocApp::InitInstance()
{
HANDLE hSep = ::CreateSemaphore(NULL,1,1,m_strAppName);
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hSep);
HWND hWnd = ::GetWindow(::GetDesktopWindow(),GW_CHILD);
while(hWnd)
{
if(GetProp(hWnd,m_strAppName))
{
if(::IsIconic(hWnd))
::ShowWindow(hWnd,SW_RESTORE);
::SetForegroundWindow(hWnd);
return FALSE;
}
hWnd = ::GetWindow(hWnd,GW_HWNDNEXT);
}
return FALSE;
}
AfxEnableControlContainer();
......
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
// .....
::SetProp(m_hWnd,theApp.m_strAppName,(HANDLE)1);
return 0;
}
void CMainFrame::OnDestroy()
{
CFrameWnd::OnDestroy();
// TODO: Add your message handler code here
RemoveProp(m_hWnd,theApp.m_strAppName);
}
单例应用控制
本文介绍了一个使用信号量和窗口属性来确保应用程序实例唯一性的方法。通过创建信号量并检查是否已有相同名称的应用实例运行,可以避免多次启动同一程序。同时,如果发现已有实例,则将该实例置为前台。
1867

被折叠的 条评论
为什么被折叠?



