Dlg app finds another copy of itself running and does SetForegroundWindow
I'm preparing an Mfc dialog application. I want to be able to find and invoke a previously invoked instance of this application ... i.e., I don't want two instances running at the same time. The second instance should detect this and bring the previously started instance to the foreground before exiting.
I'm using a mutex to determine if another instance is already running. This works fine. However, I'm having trouble finding the other instance in order to foreground it. I've seen several examples of using SetProp and GetProp, but these don't seem to work with a CWinApp dialog based app. In the code below, I suspect I'm not using the proper hWnd in the calls to SetProp and GetProp.
I was going to use another technique involving FindWindow of a registered class, but I understand this involves changing the window class name from "#32770" to another name. I was trying to do this in PreCreateWindow, but oddly, my overridden PreCreateWindow isn't called. My app dynamically modifies the title bar, so I don't think I can do a FindWindow of the window name itself.
My question(s): Is there a generally accepted technique for an Mfc dialog based app to find and foreground a previously invoked instance of itself? If this involves PreCreateWindow, how is it set up so that PreCreateWindow is called by the Mfc framework? If this involves SetProp, how is this done with an Mfc dialog based app so the corresponding GetProp works ok?
TIA
CMyDialogApp::InitInstance()
{
::CreateMutex(NULL, TRUE, m_pszExeName);
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CWnd* pPrevWnd = CWnd::GetDesktopWindow()->GetWindow(GW_CHILD);
while (pPrevWnd) {
HANDLE h = ::GetProp(pPrevWnd->GetSafeHwnd(), m_pszExeName);
if (h != 0) {
if (pPrevWnd->IsIconic()) {
pPrevWnd->ShowWindow(SW_RESTORE);
}
pPrevWnd->SetForegroundWindow();
pPrevWnd->GetLastActivePopup()->SetForegroundWindow();
return FALSE;
}
pPrevWnd = pPrevWnd->GetWindow(GW_HWNDNEXT);
}
TRACE("Could not find previous instance main window!\n");
return FALSE;
}
...
BOOL flag = ::SetProp(m_pMainWnd->GetSafeHwnd(), m_pszExeName, (HANDLE)1);
...
}
so look at this link, it has freeware that does exactly what you are looking for. I've used it in number of my apps, so I know it works.
http://www.naughter.com/sinstance.html
Hope it helps