Home | Software | Technologies | Clients | Printing | News | Delphi | Contact

Back to main page

{*****************************************************************************}
// The code below demonstrates the use of the CreateMutex function which checks
// for a previous instance of your application in the memory.  In this particular
// case if your application is already running and you try to run it again, you will
// get an error message 'Instance of this application is already running.'
// This code is especially useful when creating a screen saver or any other type
// of application which is supposed to run in a single instance mode.
//
// Author:     Pawel Michalowski, B.Sc.Cs.
// E-Mail:     pawel (at) michalowski (dot) net
// Web:        http://www.winshots.com/delphi/
//
// Copyright © 2009 Pawel Michalowski. All Rights Reserved.
// Copyright © 2009 Winshots Technologies, Inc. All Rights Reserved.
{*****************************************************************************}

{
  Disclaimer: The following code is FREE and it is provided on the "AS-IS" bases.
  Winshots Technologies or Pawel Michalowski will not take any responsibility
  whatsoever for any unwanted effects such as loss of profit, damage or otherwise
  caused by the use of this sample code.
  BY DOWNLOADING AND USING THIS SOURCE CODE, YOU INDICATE YOUR ACCEPTANCE OF THESE
  TERMS AND CONDITIONS.
}

program sample;

uses
  Forms,
  Windows,
  Unit1 in 'Unit1.pas' {Form1},
  Globals in 'Globals.pas';

{$R *.RES}
var
     MutexHandle: THandle;
     hPrevInst: Boolean;

begin
     // -== Check to see if the named mutex object existed before this call ==-
 	MutexHandle := CreateMutex(nil, TRUE, 'MysampleAppMutex');
 	if MutexHandle <> 0 then
  	begin
          if GetLastError = ERROR_ALREADY_EXISTS then
    	     // -== set hPrevInst property and close the mutex handle ==-
          begin
               MessageBox(0, 'Instance of this application is already running.',
                             'Application already running', mb_IconHand);

	       hPrevInst := TRUE;
  	       CloseHandle(MutexHandle);
               Halt; // 'Halt' Is the actual one that prevents a second instance
                     // of your app from running.
          end
   	     else
              begin
    	              // -== indicate no previous instance was found ==-
                   hPrevInst := FALSE;
              end;
   	end
     else
         begin
   	         // -== indicate no previous instance was found ==-
 	         hPrevInst := FALSE;
         end;

  Application.Initialize;
  Application.Title := 'My sample app';
  Application.HelpFile := 'sample.hlp';
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.
Other solutions...



Copyright © 1999-2009, Winshots Technologies, Inc. All Rights Reserved.