Delphi - How to prevent Forms/MsgBoxes to move under prior form?

后端 未结 4 645
刺人心
刺人心 2020-12-13 03:03

Many times after the Windows 98 era we have experienced that some dialogs lose their Z-Order and move back to the prior form.

For example:

Dialog1.Sh         


        
4条回答
  •  难免孤独
    2020-12-13 03:31

    A trick I've used recently was to apply these two lines of code during the creation of each form:

    SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or 
      WS_EX_APPWINDOW or WS_EX_TOPMOST);
    SetWindowLong(Handle, GWL_HWNDPARENT, GetDesktopWindow);
    

    Handle is the handle of the form (Form1.Handle). The WS_EX_APPWINDOW part makes each window appear on the task bar, remove it if you don't want that additional effect.

    For my main form I use this line:

    SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or
      WS_EX_TOPMOST);
    

    I also use this function to help build my custom dialogs (I created a new function for each style of dialog - error, confirmation, etc.):

    function CustomDlg(const AMessage : string; const ADlgType: TMsgDlgType;
      const AButtons: TMsgDlgButtons; const ADefaultButton: TMsgDlgBtn) : TForm;
    begin
      Result := CreateMessageDialog(AMessage, ADlgType, AButtons, ADefaultButton);
      with Result do
        begin
          SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or 
            WS_EX_APPWINDOW or WS_EX_TOPMOST);
          SetWindowLong(Handle, GWL_HWNDPARENT, GetDesktopwindow);
          FormStyle := fsStayOnTop;
          BringToFront;
        end;
    end;
    

    The FormStyle := fsStayOnTop; part is optional, of course, but I use it to make sure my confirmation and error dialogs are always visible to the user.

    It seems like a bit of work but the net effect is that I no longer have to worry about forms accidentally hiding behind other forms.

提交回复
热议问题