Single Instance of an Application Class

The question of how to force only one instance of an application to run at a time is often asked. Although this is not a difficult problem to solve, and indeed can be solved in several different ways, it comes up enough to create the need for a nice, canned solution. So here it is.

The class is called CSingleInstance, and is used as follows:

Include the header file to your CWinApp derived class's .H file:

#ifndef __AFXWIN_H__
 #error include 'stdafx.h' before including this file for PCH

#include "resource.h"       // main symbols
#include "SingleInstance.h"

Create a public member variable in you CWinApp derived class:

class CMyApp : public CWinApp
    CSingleInstance m_singleInstance;

In InitInstance, call the classs Create() function with your main frames resource identifier (usually IDR_MAINFRAME):

BOOL CMyApp::InitInstance()
    // Check if an instance of our application is already running
    if ( !m_singleInstance.Create( IDR_MAINFRAME ) ) {
        // Return indicating that this instance
        // of the app should be shut down
        return FALSE;


If the Create() function fails, the application is already running AND the running instance will be brought to the foreground. If the Create() function succeeds, then this is the first instance of the application.

In order to make this work, there is one more piece of code that needs to be inserted. In you main frames (usually CMainFrame) PreCreateWindow() function, add the following:

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
    // TODO: Modify the Window class or styles here by modifying
    // the CREATESTRUCT cs
    CMyApp *app = (CMyApp *)AfxGetApp();
    // Set the class name to be the app's single instance class name
    cs.lpszClass = app->m_singleInstance.GetClassName();

Thats how to use it. If youre interested, heres how it works.

The Create() function for CSingleInstance contains two protected members: a mutex (m_hMutex ) and a class string (m_strClassName). The mutex is used as the mechanism for actually determining if the application is already running. If the CreateMutex() function succeeds, the application is the first instance. If it fails, the mutex has already been created by another instance of the application. The class string is used as a means of finding the main window of the application. It is created by taking the name of the application (pulled from the resource string) and appending " Class" to the end. Simple but effective. It gets attached to the main window during the main frames PreCreateWindow() function. When we want to find the window, we use FindWindowEx() with the class string.

Download demo project - 19KB

Download source - 2KB

This article was originally published on August 6th, 1998
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date