Search code examples
delphiformssize

saving the Maximized and form size on a Delphi TForm


This question seems easy but for some reason I have trouble finding the answer.

I have an application that saves the form's size and position on an INI file. That's all an well, however when you close the application when maximized it will save the size and position of the form maximized but not its state.

What I mean is that on the next run the form would appear maximized when in fact it's "restored" but covering the whole desktop.

Is there a way to save the form size previous to the maximize event, then save the fact that the form is maximized. The on the read from the INI file create the form in a maximized state and set its "restore" size to the one before the maximize event?

thanks!


Solution

  • Use the Windows API function GetWindowPlacement(), like so:

    procedure TForm1.WriteSettings(AUserSettings: TIniFile);
    var
      Wp: TWindowPlacement;
    begin
      Assert(AUserSettings <> nil);
    
      if HandleAllocated then begin
        // The address of Wp should be used when function is called
        Wp.length := SizeOf(TWindowPlacement);
        GetWindowPlacement(Handle, @Wp);
    
        AUserSettings.WriteInteger(SektionMainForm, KeyFormLeft,
          Wp.rcNormalPosition.Left);
        AUserSettings.WriteInteger(SektionMainForm, KeyFormTop,
          Wp.rcNormalPosition.Top);
        AUserSettings.WriteInteger(SektionMainForm, KeyFormWidth,
          Wp.rcNormalPosition.Right - Wp.rcNormalPosition.Left);
        AUserSettings.WriteInteger(SektionMainForm, KeyFormHeight,
          Wp.rcNormalPosition.Bottom - Wp.rcNormalPosition.Top);
        AUserSettings.WriteBool(SektionMainForm, KeyFormMaximized,
          WindowState = wsMaximized);
      end;
    end;