zakalawe
zakalawe

Reputation: 11

Detecting multiple launches of a Windows application

What's the approved way to handle second, third, etc launches of application in Windows (C++) application? I need the running (first) instance to take some special action (pop up a dialog) in this case, but for the secondary instances to terminate.

On Mac, AppleEvents sends you a 're-open' message in this scenario. Mozilla on Windows uses DDE to check for an existing instance and pass the command line through. It feels like a pretty nasty solution, all the same.

Upvotes: 1

Views: 357

Answers (4)

Skizz
Skizz

Reputation: 71110

There is one issue with CreateMutex method that you might need to consider - the named mutex might have been created by a third party. Now, most of the time, this won't be an issue, there would be no reason for someone else to block your application. However, if you're making a program that does something important, it may be an issue. Consider, if your program was a virus scanner, a virus could disable it by creating the mutex.

Usually, CreateMutex should do the job, but you should be aware of the limits of this method.

Upvotes: 0

Todd
Todd

Reputation: 2401

How to limit 32-bit applications to one instance in Visual C++

"The method that is used in this article is the one that is described in MSDN under the WinMain topic. It uses the CreateMutex function to create a named mutex that can be checked across processes. Instead of duplicating the same code for every application that you will use as a single instance, the code that you must have is in a C++ wrapper class that you can reuse across each application."

SendMessage Function

"Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message."

"Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication."

RegisterWindowMessage "The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system. The message value can be used when sending or posting messages."

Upvotes: 2

Blindy
Blindy

Reputation: 67487

The windows way is to open a named mutex and, if you can acquire it, it means you're the first instance, if not, there is another one. At this point you can register a windows message (the function is literally RegisterWindowsMessage) which gives you a WM_ msg you can send to all windows and only your app would know to catch it, which allows you to tell your initial copy to open a dialog box or w/e.

Upvotes: 6

RageZ
RageZ

Reputation: 27323

On windows there is not really solution for that at least not out of the box.

You can use mutex to do such things, basically the app check for the mutex at startup create it if it doesn't exist.

Upvotes: 1

Related Questions