记忆Delphi窗体上控件的位置和大小
如果允许用户在运行时移动控件和调整控件大小,你必须确保在窗体关闭时保存控件的位置,窗体创建/加载时恢复每个控件的位置。以下是如何在INI文件中存储的每个窗体上的控件的左,上,宽度和高度属性。
接下来的两个程序WriteControlPlacement和ReadControlPlacement用Delphi的ini文件来存储和恢复窗体上每一个控制的位置属性:
~~~~~~~~~~~~~~~~~~~~~~~~~
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*)
~~~~~~~~~~~~~~~~~~~~~~~~~
注:在窗体的OnCreate事件处理程序中调用ReadControlPlacement。在窗体的OnClose或OnDestroy事件处理程序中调用WriteControlPlacement。