需求:MFC 程序最小化到托盤/後台,雙擊桌面快捷方式/可執行文件時,不啟動新實例,而是顯示/恢復已有主窗口。
CMutex mutex(FALSE, _T("Global\\MyAppUniqueMutexName"), &bCreated);!bCreated (互斥體已存在) → 已有實例運行。FindWindow 找到主窗口 → PostMessage(WM_USER_SHOW)。 /restore。
BOOL CMyApp::InitInstance() {
CMutex mutex(FALSE, _T("Global\\MyAppMutex"), &bCreated);
if (!bCreated) {
// 已運行,發送喚醒
CWnd* pWnd = CWnd::FindWindow(_T("MyMainFrameClass"), NULL);
if (pWnd) pWnd->PostMessage(WM_USER_RESTORE);
return FALSE; // 退出當前實例
}
// 解析命令行參數
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// 若需區分「雙擊快捷方式喚醒」與「命令行帶參啟動」,可自定義參數
// m_lpCmdLine 獲取完整命令行字符串
if (strstr(m_lpCmdLine, "/restore")) {
// 標記主窗口初始化時調用 ShowWindow(SW_RESTORE)
}
// ... 正常初始化
}
"C:\Path\MyApp.exe" /restore/restore → 程序邏輯識別為喚醒操作。
LRESULT CMainFrame::OnUserRestore(WPARAM, LPARAM) {
if (IsIconic()) ShowWindow(SW_RESTORE);
SetForegroundWindow();
return 0;
}
**關鍵點**:互斥體保證單實例,命令行參數/消息傳遞喚醒意圖,主窗口響應恢復顯示。此為 Windows 桌面應用標準單實例喚醒模式。