Click here to Skip to main content
15,867,488 members
Articles / Desktop Programming / MFC

How to check if an application is already running

Rate me:
Please Sign up or sign in to vote.
2.86/5 (11 votes)
27 Mar 2009CPOL1 min read 84.5K   27   10
How to determine if an application is already running and switch to it.

Introduction

For a project of my own, I had the task to check if the same application is already running every time the application is started by the user. If the application is already running, it must be switched to the foreground and the currently started process must be closed.

Using the code

I am using the Visual C++ 9.0 Standard Edition and the project type is MFC. We will use functions from <tlhelp32.h>. I am using WinXP.

In the string-table of your resource, you must have a string with the ID AFX_IDS_APP_TITLE.

It must contain the application name of your executable without .exe. For example, if your executable file is named “frTKO.exe”, then the string-resource must be “frTKO”.

First, we will include the necessary header file.

C++
#include <tlhelp32.h>

The function to do our work is as follows:

C++
// Checks, if an application with this name is running
//
// bShow ..... TRUE: bring application to foreground, if running 
//             FALSE: only check, don't move to the application
//
// return: FALSE: application is not running
//         TRUE: application runs
BOOL AppIsAllreadyRunning(BOOL bShow/*=TRUE*/)
{
    BOOL bRunning=FALSE;
    CString strAppName;
    strAppName.LoadString(AFX_IDS_APP_TITLE);
    strAppName += _T(".exe");
    DWORD dwOwnPID = GetProcessId(GetCurrentProcess());
    HANDLE hSnapShot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    PROCESSENTRY32* processInfo=new PROCESSENTRY32;
    processInfo->dwSize=sizeof(PROCESSENTRY32);
    int index=0;
    while(Process32Next(hSnapShot,processInfo)!=FALSE)
    {
        if (!strcmp(processInfo->szExeFile,strAppName))
        {
            if (processInfo->th32ProcessID != dwOwnPID)
            {
                if (bShow)
                    EnumWindows(ShowAppEnum,processInfo->th32ProcessID);
                bRunning=TRUE;
                break;
            }
        }
    }
    CloseHandle(hSnapShot);
    delete processInfo;
    return bRunning;
}

To get access to the window of the running application, we use EnumWindows(), which needs a helper-function for enumerating processes:

C++
// Helper callback-function for function AppIsAllreadyRunning()
// see description of EnumWindows() for details
BOOL CALLBACK ShowAppEnum (HWND hwnd, LPARAM lParam)
{
    DWORD dwID;
    CString strAppName;
    strAppName.LoadString(AFX_IDS_APP_TITLE);
    GetWindowThreadProcessId(hwnd, &dwID) ;
    if(dwID == (DWORD)lParam)
    {
        char title[256];
        CString strBuffer;
        GetWindowText(hwnd,title,256);
        strBuffer = title;
        if (strBuffer.Left(strAppName.GetLength()) == strAppName)
        {
            if (!IsWindowVisible(hwnd))
                ShowWindow(hwnd,SW_SHOW); 
            SetForegroundWindow(hwnd);
        }
    }
    return TRUE;
}

Now, you place a call to your function as the first in the InitInstance() of your app-class. You can check the return-code of the function to return FALSE if an instance is already running.

C++
BOOL CfrTeakoApp::InitInstance()
{
#ifndef _DEBUG
    if (AppIsAllreadyRunning())
        return FALSE;
#endif

Don’t forget to define the functions in the header-file:

C++
BOOL AppIsAllreadyRunning(BOOL bShow=TRUE);
BOOL CALLBACK ShowAppEnum( HWND hwnd, LPARAM lParam );

That’s all.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Austria Austria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
Charles Oppermann2-Aug-11 19:47
Charles Oppermann2-Aug-11 19:47 
Questionerror C2065: 'ShowAppEnum' : undeclared identifier Pin
vudvpro24-Mar-11 0:33
vudvpro24-Mar-11 0:33 
GeneralMy vote of 1 Pin
cccfff7776-Aug-10 4:46
cccfff7776-Aug-10 4:46 
Why not hold a mutex in the application and prevent a second start by obtaining ownership? Also going through the image-name, bin-file-name or the window-title is absolutely not reliable!
GeneralIt is a wrong way! Pin
Victor Nijegorodov30-Mar-09 22:18
Victor Nijegorodov30-Mar-09 22:18 
GeneralMy vote of 1 [modified] Pin
Victor Nijegorodov30-Mar-09 22:09
Victor Nijegorodov30-Mar-09 22:09 
General[My vote of 1] I'm afraid this is not the right way to do it. PinPopular
wtwhite30-Mar-09 18:31
wtwhite30-Mar-09 18:31 
GeneralGood article but ... Pin
Nacereddine28-Mar-09 0:22
professionalNacereddine28-Mar-09 0:22 
GeneralRe: Good article but ... Pin
kcynic30-Mar-09 15:08
kcynic30-Mar-09 15:08 
GeneralRe: Good article but ... Pin
VaKa30-Mar-09 20:25
VaKa30-Mar-09 20:25 
GeneralRe: Good article but ... Pin
Martin Jimenez31-Mar-09 5:02
Martin Jimenez31-Mar-09 5:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.