Windows CE: Preventing Multiple Instances of an Application

<< Windows CE: Get Process Name using GetModuleFileName | Home | Summary of BIB File Posts >>

There is often a good reason to allow only one instance of an application to run at any time. One example of this is the serial debug menu application that I present in Windows CE: Serial Debug Menu Summary. If that application were to have more than one instance the results would be unpredictable, unless you count user confusion. The input would randomly go to instance of the application based on which instance looked for input first.

One way to prevent multiple application instances is to use a mutex. The first instance would create the mutex, and subsequent instances would get a handle to an existing instance. If the mutex already exists, GetLastError will return a value that indicates that the mutex already exists.

Example:

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int  nCmdShow)

{

                HANDLE hMutex;

                hMutex = CreateMutex(NULL, TRUE, TEXT("ADSSystemTest"));

                if (GetLastError == ERROR_ALREADY_EXISTS)

{

                                RETAILMSG(1, (TEXT("Application is running already\r\n")));

                                CloseHandle( hMutex );

                                return 0;

                }

                // Do some application functions here.

                CloseHandle( hMutex );

                return 1;

}

Honestly, the calls to CloseHandle are overkill as the handles are documented to be automatically closed when the application exists, but I don’t like to leave these things to chance.

Copyright © 2009 – Bruce Eitman

All Rights Reserved

Tuesday, January 6, 2009 8:57 PM

This article is part of the GWB Archives. Original Author: Bruce Eitman

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.