Delphi XE2, how to keep form ON TOP after changing VCL styles
-
07-06-2021 - |
Question
I encountered a weird issue with XE2:
I'm using HWND_TOPMOST with SetWindowPos to set my form on top, but if I switch VCL styles at runtime, the window isn't topmost anymore, and unsetting/re-setting it doesn't fix it either.
Any way to fix this?
Solution
Your problem is that the form is being recreated because of a style change and loosing its top most style since the VCL have no knowledge of this. Either use:
FormStyle := fsStayOnTop;
or override CreateWindowHandle
so that SetWindowPos
is called each time the form is recreated:
type
TForm1 = class(TForm)
..
protected
procedure CreateWindowHandle(const Params: TCreateParams); override;
..
procedure TForm1.CreateWindowHandle(const Params: TCreateParams);
begin
inherited;
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE);
end;
BTW, I couldn't duplicate "unsetting/re-setting doesn't fix it". With my tests, calling SetWindowPos
again fixed it.
OTHER TIPS
Setting a new style on a control causes the control's window handle to be recreated, thus HWND_TOPMOST
would have to be re-applied again.
After a long search on the internet and in Delphi help with no solution, I tried several different codes, several tips, all of them with no effect whatsoever, the problem persisted. Looking at the help, I decided to test the simple code below that worked perfectly for me.
procedure TForm1.FormShow(Sender: TObject);
begin
Application.RestoreTopMosts;
end;