views:

267

answers:

3

I have rewritten a VB6 application in Delphi. It should have only one instance running. How can I do this with minimum of code?

In VB6 we just have to use one single line of code >

If App.PrevInstance Then 'Take some action End If

On goggling I did find a solution but it is very length and we have to mess with .drp file.

I do not want to do that.

I want something simpler.

+3  A: 

I have some code along the lines of:

var
    AppMutex: THandle;

{ .... }


initialization
    // Create the mutex
    AppMutex := CreateMutex(nil, True, 'MY-APPLICATION-NAME');
    if (AppMutex = 0) or (GetLastError = ERROR_ALREADY_EXISTS) then
    begin
        MessageDlg('My application is already running on this computer.'#13#10+
            'You should close the other instance before starting a new one.',mtError,
            [mbOK],0);
        Halt;
    end;

finalization
    // Close the mutex
    CloseHandle(AppMutex);

but I'm sure the answers in the thread that @mghie linked to are more helpful/richer features!

Edit: Note you can make this into a small unit in it's own right, then just use that unit in your project(s).

robsoft
A: 

In my experience one cannot decide in general wether an application my be started twice or not. It may be for instance perfectly valid to start the same application if it is started in another folder or under another user account or whatever. On the other hand it might be the case that two different applications may not run together if they are started in the same folder or so.

So besides the different approaches with mutexes and semaphores and handling race conditions, it is the wise selection of the mutex's or semaphore's name that handles the above combinations appropriately.

If an application may not run twice at all, take a GUID like name. You can even use the exe's filename if you can ignore that someone might rename it.

Restricting the one-time-start on a specific folder, you can take the exe path into account, but be aware that due to mappings different pathes may end up at the same exe.

Uwe Raabe
+2  A: 

Note that in many cases, the user's expecation will be that launching the second instance results in the first instance being restored and brought to the foreground. Don't expect users to understand the difference between restoring a minimized/hidden app and launching from a shortcut or start menu.

Chris Thornton
Welcome to Stack Overflow. What you've posted here does not *answer* the question, so it doesn't belong in the answer section. It belongs in the comments. Once you've gained 50 reputation points, you'll be allowed to post comments to other people's questions and answers instead of just your own. Beware that answers that don't actually answer the question are prone to be voted down.
Rob Kennedy