Delphi tips by Stanimir Simeonoff. The site is still under construction! The page's added to get the tips only

case 'your need' of:
My program should be run once only: read it;
I have to access a protected method: read it

else back to index

You're the th visitor of the tip page.

When I decide I write enough tips I will jazz the page...

Here is the example, explainations are below:

program RunOnce;
uses Forms, Windows,Messages...

{$R *.RES}

var
   mutex:Cardinal;
begin
  mutex:=CreateMutex(nil,true,'My program is RuNNiNG'); //Mutex is owned by this thread
// if the thread is interrupted the mutex is gone


  if GetLastError=ERROR_ALREADY_EXISTS then //first time there shouldn't be such a 'Mutex' name
  begin //otherwise the program is currently running, so halt it!
    MessageBeep (MB_ICONASTERISK);
    MessageBoxEx (0,'The programm is running.'+#10#13+' You don''t need a second copy of it', 'Your title',MB_OK+MB_ICONWARNING+MB_TASKMODAL,LANG_ENGLISH); // change values to satisfy your needs
// BUT without 0; the window should be unowned.
    Halt;
  end;

  Application.Initialize;
.....
  Application.Run;
  if mutex<>0 then CloseHandle(mutex);
end.

I knew the way and I thought "it's simple enoght" when I saw a solving of the problem in the tips of ZDNet tips. It seems whis way:

Back to Top
procedure TForm1.FormCreate(Sender: TObject);
begin
{Searchs table to see if the program is already running}
if GlobalFindAtom('PROGRAM_RUNNING') = 0 then
{ If not found then add it }
atom := GlobalAddAtom('PROGRAM_RUNNING')
else begin
{ If program is already running show message and halt }
MessageDlg('You have the program running all ready!!', mtWarning,
[mbOK], 0);
Halt;
end;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
{Removes the item from the table so it can be run again}
GlobalDeleteAtom(atom);
end;
The idea is adding a global atom which is accessible by each thread, so when another copy is about to be executed it sees the global atom and terminates itself. Although it looks plain it contains one mistake: if the program is abnormally terminated (for example: an unpredictable situation occurs and the user is forced to use Ctrl+Alt+Del) the global atom persits, so... the program is unable to be run again this Windows session.

My solving is based on an owned Mutex which destroys with its owner (the thread). That's why errors or other reasons will not make the application incapabe to be run again. By the way I recall this idea is taken from Microsoft API help.


First accessing protecting methods sometimes may be able to be dangerous. Also that is not so good style of programming, but sometimes it's need. For example: Anders Melander's TGIFImage doesn't use Canvas but its handle, so it needs to call Changed method method when finish. The idea for this tip is taken from Anders Melander who is one great programmer. : TDummyClass=Class (protectedClass)

TDummyClass(protectedClass).protectedMethod;
Back to Top
1