Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure only a single instance of my application runs?

Is there support in the Delphi XE VCL for ensuring only a single instance of an application is running?

In the past, I've used library code to control a Mutex which has always seemed complicated. As I'm starting a new project in Delphi XE, I wonder if I need to dig up that old code, or if there is support built into XE already? Or is there another easy to apply code that is nice and modern?

like image 705
mj2008 Avatar asked Mar 22 '11 11:03

mj2008


People also ask

How do I make sure that only one instance of my application runs at a time?

Run the program. You have 100 seconds to run the program again in another terminal, it will fall through saying its already running. Then wait 100 seconds, it should allow you to run it in the 2nd terminal.

How do I make sure that only one instance of my application runs at a time C#?

One of the most common reasons to limit the number of instances is to restrict the access to some sensitive resources. For this purpose, we use the Mutex object. This approach can be used on all three types of desktop applications (console, winforms, WPF).

How do I block multiple instances of an application?

Check the Make Single Instance option in the application properties. Save the project and then build it to create the exe. Then see if you can run 2 instances of the exe.

What is a single instance application?

A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.


2 Answers

You create a named Mutex when you start the application. Check GetLastError to see if an other instance is already running.

Put this code right after "begin" in your DPR file. Replace the GUID with one of your own. When I need a text constant that's unlikely to be used for anything else, I usually just hit Ctrl+G to get a GUID!

if CreateMutex(nil, True, '6EACD0BF-F3E0-44D9-91E7-47467B5A2B6A') = 0 then   RaiseLastOSError;  if GetLastError = ERROR_ALREADY_EXISTS then   Exit; 

It might look like the code is leaking an handle because it's not saving the return of CreateMutex. It's not. Windows will automatically release the handle when our application is terminated, and that's absolutely fine with us.

like image 137
Cosmin Prund Avatar answered Sep 28 '22 21:09

Cosmin Prund


I use JCL to do this:

program MyProgram;  uses   JclAppInst;  begin   JclAppInstances.CheckSingleInstance; // Added instance checking   Application.Initialize;   Application.CreateForm(TMainForm, MainForm);   Application.Run; end. 

Documentation for this, and the notification scheme, is at the JCL Wiki.

like image 44
Clóvis Valadares Junior Avatar answered Sep 28 '22 20:09

Clóvis Valadares Junior