☆TToolButtonの実行時作成&削除

あまり使うことはないと思うのですが、ファイルにキャプション一覧を登録しておき、それを読み込んでToolButtonに設定する処理です。 ポイントは、ToolBarのAutoSizeとShowCaptionを一時的に無効にすることです。この処理により、キャプションの入れ替え時に一瞬ちらつきますが、この処理を入れないと、ボタンが設定されていく様子が見えるぐらい遅くなります。

procedure TForm1.Button1Click(Sender: TObject);
var
  SL: TStringList;
  S: String;
  I: Integer;
  TB: TToolButton;
begin
  ToolBar1.AutoSize := False;
  ToolBar1.ShowCaptions := False;
  try
    // 全てのボタンを削除します。
    for I := ToolBar1.ButtonCount -1 downto 0 do
      ToolBar1.Buttons[I].Free;

    SL := TStringList.Create;
    try
      // キャプション用リストを読み込みます。
      S := ExtractFilePath(Application.Exename) + 'List.txt';
      SL.LoadFromFile(S);
      for I := SL.Count - 1 downto 0 do
      begin
        // TToolButtonの生成
        TB := TToolButton.Create(Self);
        TB.Parent := ToolBar1;
        TB.Caption := SL[I];
        TB.OnClick := nil; // 必要なイベントを設定
      end;
    finally
      SL.Free;
    end;
  finally
    ToolBar1.ShowCaptions := True;
    ToolBar1.AutoSize :=  True;
  end;
end;

|