在 Delphi TForm上保存最大化和窗体大小

qjp7pelc  于 2023-03-08  发布在  其他
关注(0)|答案(5)|浏览(165)

这个问题看起来很容易,但不知什么原因,我很难找到答案。
我有一个应用程序,保存窗体的大小和位置的INI文件。这一切都很好,但当你关闭应用程序时,最大化它将保存大小和位置的窗体最大化,但不其状态。
我的意思是,在下一次运行时,表单将显示为最大化,而实际上它是"恢复"的,但覆盖了整个桌面。
是否有一种方法可以在最大化事件之前保存窗体大小,然后保存窗体已最大化的事实。从INI文件读取时,创建最大化状态的窗体,并将其"还原"大小设置为最大化事件之前的大小?
谢谢!

ztigrdn8

ztigrdn81#

使用Windows API函数 GetWindowPlacement(),如下所示:

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;
k97glaaz

k97glaaz2#

请尝试使用Form.WindowState属性。通过阅读该属性,可以将其写入ini文件,然后从ini读回以在www.example.com方法中重新设置状态form.show。由于WindowState是枚举类型(TWindowState),因此可能需要将其重新转换为整数。

omtl5h9j

omtl5h9j3#

Tom的答案应该很好用。下面是一些伪代码来澄清一下:

procedure TfrmDatenMonitor.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
  inherited;
  //*** Save the WindowState in every case
  aIniFile.WriteInteger(Name, 'State', Integer(WindowState));

  if WindowState = wsNormal then begin
    //*** Save Position and Size, too...
    aIniFile.WriteInteger(Name, 'Top',    Top);
    aIniFile.WriteInteger(Name, 'Left',   Left);
    aIniFile.WriteInteger(Name, 'Height', Height);
    aIniFile.WriteInteger(Name, 'Width',  Width);
  end;
end;

阅读设置时,首先设置Size和Position。然后读取WindowState并使用类型转换对其赋值:

WindowState := TWindowState(aIniFile.ReadInteger(Name, 'State', Integer(wsNormal)));
kdfy810k

kdfy810k4#

DelphiDabbler有一些不错的window state components,你只需要在你的表单上放一个,它会在表单销毁时将状态保存到ini文件或注册表中,并在表单创建时加载它。

w7t8yxp5

w7t8yxp55#

更新以显示** Delphi 11**解决方案。
请参阅Embarcadero dockwiki https://docwiki.embarcadero.com/RADStudio/Alexandria/en/Using_TIniFile_and_TMemIniFile
FMX代码:

uses System.IniFiles;

procedure TForm1.FormCreate(Sender: TObject);
var
  Ini : TIniFile;
begin
  Ini := TIniFile.Create( ChangeFileExt( ParamStr(0),'.ini' ));
  try
    if Ini.ReadBool( 'Form', 'InitMax', false ) then
      WindowState := TWindowState.wsMaximized
    else
      WindowState := TWindowState.wsNormal;
  finally
  end;
  Ini.Free;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
  Ini : TIniFile;
begin
  Ini := TIniFile.Create( ChangeFileExt( ParamStr(0),'.ini' ));
  try
    Ini.WriteBool( 'Form', 'InitMax', WindowState = TWindowState.wsMaximized );
  finally
    Ini.Free;
  end;
end;

相关问题