如何从TForm1.FormCreate初始化另一个表单?

时间:2017-06-17 13:19:11

标签: delphi

我的应用程序有多种形式。我加载TForm1.FormCreate(主窗体)的所有设置。我的配置面板是form8。

procedure TForm1.FormCreate(Sender: TObject);
begin
  settings:=TMemIniFile.Create('');
  settings.Create('settings.ini');

  if settings.ReadString('settings','ComboBox1','')='1' then 
  form1.ComboBox1.checked:=true else form1.ComboBox1.checked:=false;


  //line below crashes application because form8 has not been initialized yet
  if settings.ReadString('settings','ComboBox2','')='1' then 
  form8.ComboBox1.checked:=true else form8.ComboBox1.checked:=false;

  settings.free
end;

有没有办法强制初始化form8所以我可以在那里配置UI元素?我真的更喜欢从TForm1.FormCreate那样做。是的我知道我可以从form1.Onshow或form1.Onactivate加载设置但是这次我需要将代码放在form1.Oncreate中,因为我的应用程序也在托盘中开始最小化。

2 个答案:

答案 0 :(得分:2)

将该设置显示代码移动到您的设置表单(例如,传递配置对象的create方法)。只有在需要时才创建和显示设置表单。没有必要准备但隐藏的设置表单(当设置对象发生变化时,不会谈论它可能的同步)。

一个想法,但不是理想

type
  TFormConfig = class(TForm)
    CheckBoxSomething: TCheckBox;
  private
    procedure DisplaySettings(ASettings: TMemIniFile);
    procedure CollectSettings(ASettings: TMemIniFile);
  public
    class function Setup(AOwner: TComponent; ASettings: TMemIniFile): Boolean;
  end;

implementation

class function TFormConfig.Setup(AOwner: TComponent; ASettings: TMemIniFile): Boolean;
var
  Form: TFormConfig;
begin
  { create the form instance }
  Form := TFormConfig.Create(AOwner);
  try
    { display settings }
    Form.DisplaySettings(ASettings);
    { show form and store the result }
    Result := Form.ShowModal = mrOK;
    { and collect the settings if the user accepted the dialog }
    if Result then
      Form.CollectSettings(ASettings);
  finally
    Form.Free;
  end;
end;

procedure TFormConfig.DisplaySettings(ASettings: TMemIniFile);
begin
  CheckBoxSomething.Checked := ASettings.ReadBool('Section', 'Ident', True);
end;

procedure TFormConfig.CollectSettings(ASettings: TMemIniFile);
begin
  ASettings.WriteBool('Section', 'Ident', CheckBoxSomething.Checked);
end;

及其用法:

if TFormConfig.Setup(Self, Settings) then
begin
  { user accepted the config dialog, update app. behavior if needed }
end;

答案 1 :(得分:-1)

将您的设置代码放在DPR中:

  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm1, Form1);
  Application.CreateForm(TForm2, Form2);

  // place settings code here

  Application.Run;
end.