Mega Code Archive

 
Categories / Delphi / Forms
 

How to remember Delphi form controls position and size

Title: How to remember Delphi form controls position and size If you allow a user to move and resize form controls (at run time), you have to ensure that control placement is somehow saved when the form is closed and that each control's position is restored when the form is created / loaded. Here's how to store the Left, Top, Width and Height properties, for every control on a form, in an INI file. The next two procedures WriteControlPlacement and ReadControlPlacement can be used to store the position properties of every control on a Delphi form to an INI file: ~~~~~~~~~~~~~~~~~~~~~~~~~ procedure TForm1.WriteControlPlacement; var iniFile : TIniFile; idx : integer; ctrl : TControl; begin iniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini')) ; try for idx := 0 to -1 + Self.ComponentCount do begin if Components[idx] is TControl then begin ctrl := TControl(Components[idx]) ; iniFile.WriteInteger(ctrl.Name,'Top',ctrl.Top) ; iniFile.WriteInteger(ctrl.Name,'Left',ctrl.Left) ; iniFile.WriteInteger(ctrl.Name,'Width',ctrl.Width) ; iniFile.WriteInteger(ctrl.Name,'Height',ctrl.Height) ; end; end; finally FreeAndNil(iniFile) ; end; end; (*WriteControlPlacement*) ~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~ procedure TForm1.ReadControlPlacement; var iniFile : TIniFile; idx : integer; ctrl : TControl; begin iniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini')) ; try for idx := 0 to -1 + Self.ComponentCount do begin if Components[idx] is TControl then begin ctrl := TControl(Components[idx]) ; ctrl.Top := iniFile.ReadInteger(ctrl.Name,'Top',ctrl.Top) ; ctrl.Left := iniFile.ReadInteger(ctrl.Name,'Left',ctrl.Left) ; ctrl.Width := iniFile.ReadInteger(ctrl.Name,'Width',ctrl.Width) ; ctrl.Height := iniFile.ReadInteger(ctrl.Name,'Height',ctrl.Height) ; end; end; finally FreeAndNil(iniFile) ; end; end; (*ReadControlPlacement*) ~~~~~~~~~~~~~~~~~~~~~~~~~ Note 1: Call ReadControlPlacement in the Form's OnCreate event handler. Call WriteControlPlacement in the Form's OnClose (or OnDestroy) event handler. Note 2: Refresh your memory on the Controls and Components properties by reading the Owner vs. Parent article.