开发者

Easiest way to find previous instance of an application

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.


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).


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜