delphirules
delphirules

Reputation: 7438

How to (really) set the focus to my application?

I'm on Delphi 11 / Windows 11 and using the code below to force the focus to my application , when needed.

It works sometimes, but sometimes instead of setting the focus and bring my app Windows to front, Windows will only 'flash' my app icon on the taskbar.

Is there anything i could do to always achieve the task correctly ?

procedure setFocus;
var hand: thandle;
begin
 hand := GetForegroundWindow;
    if hand <> application.MainForm.Handle then
    begin
      try
        setForeGround(application.MainForm.Handle);
        application.showmainform := true;
      finally
      end;
end;

Upvotes: 1

Views: 642

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

Is there anything [I] could do to always achieve the task correctly ?

No.

A modern operating system like Windows 11 won't allow an app to bring itself to the foreground without the user explicitly requesting it. The user is the one who gets to decide which apps to display on his or her own desktop and which app is at the foreground.

Indeed, this is very good. It is highly annoying when apps or dialogs just pop up without the user expecting them to do so.

Mandatory reading: Foreground activation permission is like love: You can’t steal it, it has to be given to you by Microsoft developer Raymond Chen.

Upvotes: 7

Related Questions