(******************************************************************************
 *                                                                            *
 *  RunOnce - Prevents application for being launched more than once          *
 *                                                                            *
 *  Copyright (c) 2006 Michael Puff  http://www.michael-puff.de               *
 *                                                                            *
 ******************************************************************************)

 {
   Usage:
   - Add unit to project
   - Call RunOnceInit after Application.Initialize;
   - Use for the first parameter an unique string.
     For example a GUID (Globally Unique Identifier).
     (Delphi IDE: Strg+Shift+G)
}

unit MpuRunOnce;

interface

uses
  Windows;

procedure RunOnceInit(GUID: String; ShowMessage: Boolean; Handle: THandle; Caption, MsgText: String; MsgBoxFlags: DWORD = 0);

implementation

var
  hMutex: THandle;

procedure RunOnceInit(GUID: String; ShowMessage: Boolean; Handle: THandle; Caption, MsgText: String; MsgBoxFlags: DWORD = 0);
begin
  hMutex := CreateMutex(nil, True, PChar(GUID));
  if GetLastError = ERROR_ALREADY_EXISTS then
  begin
    if ShowMessage then
    begin
      MessageBox(Handle, PChar(MsgText), PChar(Caption), MsgBoxFlags);
      Halt;
    end;
  end;
end;

Initialization

Finalization
  if hMutex <> 0 then
    CloseHandle(hMutex);

end.

