ToolBar上的ToolButton单击后要刷新窗体重新创建ToolBar,问题是在单击事件后释放ToolBar时常会出问题,请高手指点!unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ToolWin, ComCtrls, StdCtrls, Buttons;type
  TForm1 = class(TForm)
    CoolBar1: TCoolBar;
    procedure FormShow(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    procedure ToolBarClick(Sender: TObject);
  public
    { Public declarations }
  end;var
  Form1: TForm1;
  ToolBar : TToolBar;
  TBtn    : TToolButton;
implementation{$R *.dfm}procedure TForm1.ToolBarClick(Sender: TObject);
begin
  if (Sender is TToolButton) then
  begin
    if (Sender as TToolButton).Name = 'Btn1' then
    begin
      Form1.Hide;
      ToolBar.Free;
      ToolBar := nil;
      Form1.Show;
    end;
  end;
end;procedure TForm1.FormShow(Sender: TObject);
begin
  CoolBar1.AutoSize := True;  ToolBar := TToolBar.Create(nil);
  ToolBar.Parent := CoolBar1;
  ToolBar.ShowCaptions := True;
  ToolBar.AutoSize := True;  TBtn := TToolButton.Create(nil);
  TBtn.Parent := ToolBar;
  TBtn.Name := 'Btn1';
  TBtn.Caption := 'Test1';
  TBtn.OnClick := ToolBarClick;
end;procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  ToolBar.Free;
end;end.

解决方案 »

  1.   

    倒死,释放toolbar之前先释放掉toolbutton
      

  2.   

    这是程序结构的问题,一般需要在一个控件的事件中删除自身,容易出现问题,用以下方法实现可能更好:
    1  在 TForm1.ToolBarClick中用PostMessage 向其他控件或窗体发送一条自定义消息。procedure TForm1.ToolBarClick(Sender: TObject);
    begin
      if (Sender is TToolButton) then
        if (Sender as TToolButton).Name = 'Btn1' then
          PostMessage(Handle, WM_USER, 0, 0);
    end;2  在消息的接收方处理你需要的逻辑。  TForm1 = class(TForm)
        ...
        procedure WMUSER(var msg: TMessage); message WM_USER;
        ...
      end;procedure TForm1.WMUSER(var msg: TMessage);
    begin
      // 你的处理
    end;
      

  3.   

    to:  xiaocha(小查)
    窗体无法关闭了!
      

  4.   

    你的ToolBar已经Free了,在FormClose中还Free?procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
      if Assigned(ToolBar) then ToolBar.Free;
    end;