Setting Focus on own Application lazarus / 31-LCL ---------------------------------------------------------------------- ArminLinder · 2016-12-30 16:28 Hi experts, I am seeking your help to overcome the following problem: I used the UniqueInstance library to ensure that only one instance of my application runs. In my experience, the main reason for a user starting a second instance is that the program is either hidden behind something else, or minimized to the taskbar. So to make uniqueinstance work like one can expect, I used the OnOtherInstance Event to bring the running instance back on screen. Unfortunately, Microsoft has made "stealing" the focus from an application hard, even if, in my case, this is the best solution for a common user problem. Without a little hack with formstyle my application would neither come back from the Taskbar, nor would it get into the foreground, instead the Taskbar icon would start to blink. The code I have now brings my application to the foregound, may it be minimized or just hidden behind another application, but it won't get the focus. This problem has been widely described for Delphi, and there were two solutions suggested, using "SetActiveWindow" or "SetForegroundWindow" (Unit: LCLIntf). Both of them don't seem to do anything. Question: how can I get my application window focused after I restored it and moved it to the foreground? Any ideas welcome, Armin. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i 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); begin  // Revert Application.restore hack #1  Self.formstyle := fsNormal;  // Restore and bring to front - works  Application.Restore;  Application.BringToFront;  // move focus - neither call does do anything  SetActiveWindow(Application.MainForm.Handle);  SetForegroundWindow(Application.MainForm.Handle);end; ---------------------------------------------------------------------- Cyrax · 2017-01-01 15:28 How about change Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i SetActiveWindow(Application.MainForm.Handle); to Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i SetActiveWindow(Self.Handle);? Your TForm1 class instance is normally the main form. ---------------------------------------------------------------------- ArminLinder · 2017-01-08 18:00 Hm, seems this doesn't do anything. If the Application is minimized, it stays minimized, if it is hidden behind some other application, it does not come to the foreground. Tested with and without the "Formstyle" Hack, just to make sure. Did you ever test this with Windows 10, or any other Windows Version, and find your code working? Armin ---------------------------------------------------------------------- ArminLinder · 2017-01-08 18:38 Finally, I got a working solution (Windows 7 and Windows 10 tested OK). If one looks at the documenations for the SetForegroundWindow in Microsft MSDN, there is a "Remarks" section with a list of restrictions, when the command would work, and when it would not. There is a note that SetForegroundWindow would work, if "The process received the last input event." So I send my own process a dummy input, and gee, now everything works like expected, when OnOtherInstance fires, my application will either restore itself from the Taskbar, and/or come to the foreground and grab the input focus. Here is the code: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i 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;  Summary: Windows does not honor the formstyle attribute, so at first glance it is pointless to set it to any value. Application.Restore will just flash the application icon but not restore it, and Application.BringToFront and SetForegroundWindow (grab Focus) won't work at all either. Hack #1: If the formstyle attribute is set to fsStayOnTop initally, the Window won't stay on top, but if the attribute is set to fsNormal later, Application.Restore and Application.BringToFront work like expected. Hack #2: the "dummy input" hack entitles my App to call SetForegroundWindow to grab the focus. Tested and found working with Windows 10 x86 and Windows 7 x64, Lazarus 1.6. Armin. ---------------------------------------------------------------------- ASerge · 2017-01-10 00:33 According to the documentation https://msdn.microsoft.com/en- us/library/windows/desktop/ms633539%28v=vs.85%29.aspx QuoteA process can set the foreground window only if one of the following conditions is true:     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. You do third case. Better, in my opinion, to fix UniqueInstance: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$IFDEF WINDOWS}function AllowSetForegroundWindow(dwProcessId: LongInt): BOOL; stdcall;  external user32;{$ENDIF}//...procedure TUniqueInstance.Loaded;//...        IPCClient.Active := True;        {$IFDEF WINDOWS} AllowSetForegroundWindow(-1); {$ENDIF} // Lines added//...Because the second instance corresponds to the requirements of case 1, it allows any app to make SetForegroundWindow, for example first instance. ---------------------------------------------------------------------- ArminLinder · 2017-01-10 22:27 Hi Serge, thanks for that nice piece of elegant code ... I modified UniqueInstance like you suggested, and it works like a charm, without all that "hack" stuff I had before. Unfortunately I spent today having another weird WIndows problem (did I mention that at times I really hate this time wasting, bloated, cryptic, awful, ill documented,  ). 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: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i      // restore from taskbar     Application.Restore;     // bring to front   Application.BringToFront;     // give focus to topmost window     // hMyWindow := GetForegroundWindow(); returns 0 if messagebox on top     // hMyWindow := GetActiveWindow(); returns other instance handle     hTopWindow := GetTopWindow(hMyWindow); // returns handle of explorer     if hTopWindow <> NULL then SetForegroundWindow(hTopWindow);  Do you have an idea what I can do? Think it should be possible to code this, since an application having a modal dialog box open can be brought to the foreground using Task Manager (or Alt-Tab), so there must be a way to find the Messagebox and pass the focus to it. Any clues welcome, Armin. ---------------------------------------------------------------------- ASerge · 2017-01-11 19:47 Quote from: Nimral on January 10, 2017, 11:27:40 pmA 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: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses InterfaceBase;//...var  AppWnd: HWND;//...  AppWnd := Widgetset.AppHandle;  if IsIconic(AppWnd) then    Application.Restore;  SetForegroundWindow(AppWnd); ---------------------------------------------------------------------- ArminLinder · 2017-01-17 20:00 Hi Serge, putting all your valuable input together, I did, indeed, get my perfect version of UniqueInstance running. Thanks very much for your help, Armin. ---------------------------------------------------------------------- CM630 · 2018-05-10 08:18 Quote from: Nimral on January 08, 2017, 07:38:05 pm Finally, I got a working solution (Windows 7 and Windows 10 tested OK). ... Here is the code: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i 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;  That won't compile, because it cannot find LPInput. I have searched the entire Lazarus for it, but I did not find a reasonable source for it. ---------------------------------------------------------------------- ArminLinder · 2018-05-10 09:44 Hi, I cannot remember either, must be from a library wrapping the sendinput windows API. I have abandoned the hacky approach to grab the focus shortly after, in favor of this one: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.UniqueInstanceOtherInstance(Sender: TObject;  ParamCount: integer; Parameters: array of string); // Instance Uniqueness handler. Brings own instance to foreground// Requires: Windows, InterfaceBase var  AppWnd: HWND;  fsOld: TFormStyle; begin  try    // Application.restore hack #1    fsOld := Self.FormStyle;    Self.FormStyle := fsStayOnTop;    Self.FormStyle := fsOld;    AppWnd := Widgetset.AppHandle;    if IsIconic(AppWnd) then    begin      // Restore from taskbar      Application.Restore;    end;    // Bring to front & set focus    SetForegroundWindow(AppWnd);  except    on e: Exception do      ;  end;end;  Does this snippet help? If not ... I am quite sure I can dig up my sources from 2017 in my Subversion server if you still need it, please let me know. Greetz, Armin. ---------------------------------------------------------------------- CM630 · 2018-05-10 10:19 Thanks! It sort of works after adding InterfaceBase in uses. But now my application gets in front and I cannot show another application in front of it, without clicking on my application first. ---------------------------------------------------------------------- ArminLinder · 2018-05-10 11:30 Interesting problem you have. Never noticed this in my applications, but frankly I am not sure whether this use-case has ever been tried. Before I fire up Lazarus to check (currently my development environment is not available) ... let me stab in the dark a little ... did you notice the "identifier" (?) property of the UniqueInstance class? It distinguishes one application from another. As long as there is only one, it won't matter. My first approach would be to check whether the identifiers for both applications are set to different values, a random GUID maybe. Armin. ---------------------------------------------------------------------- CM630 · 2018-05-10 13:30 It will take some time to understand you. Meanwhile, I found that these line do nothing but cause a single flicker of the screen: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i fsOld := Self.FormStyle;Self.FormStyle := fsStayOnTop;Self.FormStyle := fsOld; App stays in front of all the rest without them. EDIT: I have found the reason for the misbehaviour. I have left Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i    // Application.restore hack #1  Self.formstyle := fsStayOnTop; in Form.Create (from attempting to use the first code).