A process can set the foreground window only if one of the following conditions is true:You do third case.
The process is the foreground process.
The process was started by the foreground process.
The process received the last input event.
There is no foreground process.
The process is being debugged.
The foreground process is not a Modern Application or the Start Screen.
The foreground is not locked (see LockSetForegroundWindow).
The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
No menus are active.
A problem occurs if the first instance has a modal MessageBox open, neither I can bring it to the front, not can I change focus to the messagebox. there are the variants I have tried:Try this code:
Finally, I got a working solution (Windows 7 and Windows 10 tested OK).
...
Here is the code:
procedure TForm1.Form1_OnCreate(Sender: TObject); begin // Application.restore hack #1 Self.formstyle := fsStayOnTop; end; procedure TForm1.UniqueInstance1_OnOtherInstance(Sender: TObject; ParamCount: Integer; Parameters: array of String); var I: LPInput; begin // Revert Application.restore hack #1 Self.formstyle := fsNormal; // Restore and bring to front Application.Restore; Application.BringToFront; // Grab focus I := nil; try // Hack #2: send myself some dummy input GetMem(I,SizeOf(Input)); FillChar(I^, SizeOf(Input),$00); // empty input structure SendInput(1, I, SizeOf(Input)); SetForegroundWindow(Application.MainForm.Handle); finally if I <> nil then FreeMem(I,SizeOf(Input)); end; end;