TIP: Dialog-Based, Single-Instance Applications

Introduction

There are lots of articles on CodeGuru about limiting your program to a single instance. In this article, I want to show how easily it can be done by simply modifying the dialog template and adding few lines of code in InitInstance(). Although I use MFC for this sample, you can use the same technique for ATL/WTL and generic Win32 applications.

Implementation

  • Create an MFC dialog-based project.
  • Open the Resource Script file (.rc), find your main dialog template, and add the following lines:
    CLASS "SINGLE_INSTANCE_APP"
    
    IDD_SINGLEINSTANCE_DIALOG DIALOGEX 0, 0, 320, 200
       STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS |
             WS_POPUP | WS_VISIBLE |
             WS_CAPTION | WS_SYSMENU
       EXSTYLE WS_EX_APPWINDOW
       CLASS "SINGLE_INSTANCE_APP"
       CAPTION "Single Instance Application"
       ...
    

    This will instruct Windows to use your own windows class "SINGLE_INSTANCE_APP" instead of a standard dialog class.

  • Now, you have to register the "SINGLE_INSTANCE_APP" windows class. The best place for this is InitInstance().
  •    WNDCLASS wc = {0};
       wc.style = CS_BYTEALIGNWINDOW|CS_SAVEBITS|CS_DBLCLKS;
       wc.lpfnWndProc = DefDlgProc;
       wc.cbWndExtra = DLGWINDOWEXTRA;
       wc.hInstance = m_hInstance;
       wc.hIcon = LoadIcon(IDR_MAINFRAME);
       wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
       wc.hbrBackground =
          CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
       wc.lpszClassName = _T("SINGLE_INSTANCE_APP");
       ATOM cls = RegisterClass(&wc);
    
  • After this, you can find your main dialog by its class name.
  • CWnd* pWnd =
       CWnd::FindWindow(_T("SINGLE_INSTANCE_APP"), NULL);
    if (pWnd)
    {
       pWnd->ShowWindow(SW_SHOW);
       pWnd->SetForegroundWindow();
       return FALSE;
    }
    


About the Author

Khachatur Petrosyan

View http headers, analyze http traffic with HTTP Debugger

Downloads