unit SingleInst;

interface

uses Windows, Messages;

// Main window (window of class MainWndClass) must process this message.
// Message.Result should be 1.
const
   WM_TESTMAININSTANCE = WM_USER + 101;

// Checkes another instance. If Another instance exists and
// processes message WM_TESTMAININSTANCE, Result us True.
function CheckOtherInstance(const MainWndClass: PChar): Boolean;

implementation

uses SysUtils;

var
  LastFound: HWND;

function LookAtAllWindows(Handle: HWND; WndClass: LongInt): BOOL; stdcall;
var ClassName: Array[0..255] of Char;
  function SendParam(aHandle: hWND): Boolean;
  var S: String;
      Atom: TAtom;
  begin
    if ParamCount > 0 then S := ParamStr(1) else S := '';
    Atom := GlobalAddAtom(PChar(S));
    Result := SendMessage(aHandle, WM_TESTMAININSTANCE, Atom, 0) = 1;
    GlobalDeleteAtom(Atom);
  end;
begin
  Result:= True;
  if (GetClassName(Handle, ClassName, SizeOf(ClassName)) > 0) and
     (StrComp(ClassName, PChar(WndClass)) = 0) and
     SendParam(Handle) then
    LastFound := Handle;
end;

function CheckOtherInstance(const MainWndClass: PChar): Boolean;
begin
  LastFound := 0;
  EnumWindows(@LookAtAllWindows, Integer(MainWndClass));
  Result := LastFound <> 0;
end;

end.
