single instance dialog

I have a dialog application and I only want a single instance of it running at one time.  How can I do this.  I have tried these articles and they didn't seem to work for me:
I must be missing something obvious so I've decided to take a step back and pretend I didn't read any of them and ask how to do it.
Who is Participating?
Those techniques *do* work.  Here is my version:

#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H

#include <windows.h>

//this code is from Q243953 in case you lose the article and wonder
//where this code came from...
class CLimitSingleInstance
  DWORD  m_dwLastError;
  HANDLE m_hMutex;

  CLimitSingleInstance(TCHAR *strMutexName)
    //be sure to use a name that is unique for this application otherwise
    //two apps may think they are the same if they are using same name for
    //3rd parm to CreateMutex
    m_hMutex = CreateMutex(NULL, FALSE, strMutexName); //do early
    m_dwLastError = GetLastError(); //save for use later...
    if (m_hMutex)  //don't forget to close handles...
       CloseHandle(m_hMutex); //do as late as possible
       m_hMutex = NULL; //good habit to be in

  BOOL IsAnotherInstanceRunning()
    return (ERROR_ALREADY_EXISTS == m_dwLastError);
#endif  //#ifndef LimitSingleInstance_H


Then in the app...

CLimitSingleInstance g_SingleInstanceObj( "CreditBaseApp" ); // checked in InitInstance

in InitInstance...

   //------------------------------------ avoid running two copies
    if ( g_SingleInstanceObj.IsAnotherInstanceRunning() ) {
        CWnd* pWnd=  CWnd::FindWindow( NULL, CSTR_AppWinTitle );
        if ( pWnd )   {
              CWnd* pWndChild= pWnd->GetLastActivePopup(); // If so, does it have any popups?
            // if ( pWnd->IsIconic() ) {            // If iconic, restore the main window
            if ( !pWnd->IsWindowVisible() ) {            // If iconic, restore the main window
                    pWnd->ShowWindow(SW_RESTORE); // tray app stuff
              pWndChild->SetForegroundWindow(); // Bring the main window or its popup to the foreground
        return FALSE; // dont start this instance
.... else, run normally ...

-- Dan
dociebAuthor Commented:
Ahh, dumb me.  I figured out what I was doing.  I forgot that I changed the folder that I was placing the release in and I kept trying it with older version.  I used yours and it works and the others probably works also.  Man the last few hours was a waste of time.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.