This example activates previous instance of application:
uses LazUTF8, Windows;
var
InterprocVarHandle:Handle = 0;
InterprocVar:PHandle = nil;
function AlreadyRunning:boolean;
const
ApplicationSecretString = 'qweqweqweqweqweqweqweqwe';
var
Str:UnicodeString;
AlreadyCreated:Boolean;
begin
Str:= UTF8ToUTF16(ApplicationSecretString);
// Create an interprocess variable
InterprocVarHandle:= CreateFileMappingW(Handle(-1),Nil,PAGE_READWRITE,0,SizeOf(InterprocVar^),@Str[1]);
if InterprocVarHandle = 0 then exit(true);
AlreadyCreated:= GetLastError = ERROR_ALREADY_EXISTS;
// Get a pointer to the variable
InterprocVar:= MapViewOfFile(InterprocVarHandle,FILE_MAP_ALL_ACCESS,0,0,SizeOf(InterprocVar^));
if InterprocVar = nil then exit(true);
if AlreadyCreated then exit(true);
// Write main form's handle to the interprocess variable
InterprocVar^:= Form1.Handle;
Result:= false;
end;
procedure ActivatePreviousInstance;
var
PrevMainForm:Handle;
begin
if InterprocVar <> nil then begin
// Read previous main form handle from the interprocess variable
PrevMainForm:= InterprocVar^;
SendMessage(PrevMainForm,WM_SYSCOMMAND,SC_RESTORE,0);
SetForegroundWindow(PrevMainForm);
end;
end;
procedure TForm1.FormCreate(Sender:TObject);
begin
if AlreadyRunning then begin
ActivatePreviousInstance;
halt;
end;
end;