Senin, 04 Januari 2010

Delphi - Single application instance

Source :http://www.ibrtses.com/delphi/singleinstance.html

Delphi - Single application instance
disclaimer
the source code of this page may not appear correctly in certain browsers
due to special characters. Have a look at the source of this HTML page
with notepad instead

Limiting an application to start just once per machine is usually required when an
external resource such as a Comport is accessed. This feature is achieved by allocation
of a global variable, such as a mutex.
The original version
Be the original application MyApp.dpr generated by Delphi as dpr file.

program MyApp;
uses
Windows,Forms,
MyApp1 in 'MyApp1.pas' {Form1};

{$R *.RES}

begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.


The single instance version
Do the following changes ( in bold ):

program MyApp;
uses
Windows,Forms,
MyApp1 in 'MyApp1.pas' {Form1};


var
Mutex : THandle;
{$R *.RES}

begin
Mutex := CreateMutex(nil, True, 'MyAppName');
if (Mutex <> 0) and (GetLastError = 0) then
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
if Mutex <> 0 then
CloseHandle(Mutex);
end;
end.


The application will only start once at a time without any further notice.
Any further attempts will be defeated.

A little addition, perhaps as modal notice, could notify the user
that only one is allowed at a time.


1 komentar:

  1. I will put this in a component so i can use it more simple:)

    http://www.components4developers.com

    BalasHapus

INGIN KERJA DARI RUMAH?