【问题标题】:How to initialize another form from TForm1.FormCreate?如何从 TForm1.FormCreate 初始化另一个表单?
【发布时间】:2017-06-17 13:19:11
【问题描述】:

我的申请有多种形式。我在 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,因为我的应用程序也开始在托盘中最小化。

【问题讨论】:

  • 声明一个接收必要信息的构造函数。
  • 确实,与其让主表单管理其他表单的显示,不如反其道而行之。其他表单应读取主表单。或者更好的是,来自整个应用程序全局共享的后台对象。
  • 在 TForm1.FormCreate 中对 form1 的引用是不好的做法 - 使用 ComboBox1.Checked := True。这将始终引用 TForm1 的当前实例,而不是特定实例。整个块也可以替换为ComboBox1.Checked := settings.ReadString('settings', 'ComboBox1','') = '1'

标签: delphi


【解决方案1】:

将该设置显示代码移动到您的设置表单(例如,将配置对象传递到其中的创建方法)。并且仅在需要时创建和显示该设置表单。无需准备但隐藏的设置表单(不说设置对象更改时可能的同步)。

一个想法,但不是理想

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;

【讨论】:

    【解决方案2】:

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

      Application.Initialize;
      Application.MainFormOnTaskbar := True;
      Application.CreateForm(TForm1, Form1);
      Application.CreateForm(TForm2, Form2);
    
      // place settings code here
    
      Application.Run;
    end.
    

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多