Modify your *.DPR project file with the example below:
Program PrevInst;
USES
Forms, Windows, // Add Windows
Unit1 in 'Unit1.pas' {Form1};
{$R *.RES}
VAR // Add Vars
MutexHandle: THandle;
hwind:HWND;
BEGIN
// Add below code
MutexHandle := CreateMutex(nil, TRUE, 'MysampleAppMutex'); // should be a unique string
IF MutexHandle <> 0 then
begin
IF GetLastError = ERROR_ALREADY_EXISTS then
begin
// MessageBox(0, 'Instance of this application is already running.',
// 'Application already running', mb_IconHand);
CloseHandle(MutexHandle);
hwind := 0;
repeat
// The string 'My app' must match your App Title (below)
hwind:=Windows.FindWindowEx(0,hwind,'TApplication','My app');
until (hwind<>Application.Handle);
IF (hwind<>0) then
begin
Windows.ShowWindow(hwind,SW_SHOWNORMAL);
Windows.SetForegroundWindow(hwind);
end;
Halt;
end
end;
// your/Delphi's window create / run code is below here:
Application.Initialize;
Application.Title := 'My app'; // this matches to above
Application.CreateForm(TForm1, Form1);
Application.Run;
END.
A shorter method (without automatic switching to your app's original instance) would be:
CreateMutex(nil,FALSE,'AnyNameHere');
IF GetLastError = ERROR_ALREADY_EXISTS THEN
begin
MessageDlg('Program is already running. You can not start more than one instance',
mterror,[mbOK], 0);
Halt(0);
end;
Application.Initialize;