Search code examples
delphilazarus

Remove a tab at runtime via containing form's button


I'm creating tabs at run-time like this:

procedure TForm1.ShowFormOnTab(pProcName:String);
var
  Newform: TForm;
  ClassToUse: TFormClass;

  NewTab: TTabSheet;
  FormName: String;

begin
  NewTab := TTabSheet.Create(PageControl1);
  NewTab.PageControl:= PageControl1;

  PageControl1.ActivePage :=  NewTab;

  if pProcName='ProcfrmSetupItemCategories' then
    ClassToUse := TfrmSetupItemCategories
  else if pProcName='ProcfrmZones' then
    ClassToUse := TfrmZones
  else
    ClassToUse := nil;
  if Assigned(ClassToUse) then
    begin
      NewForm := ClassTouse.Create(NewTab);
      NewTab.Caption := NewForm.Caption;
    end;

Now, the tabs show correctly, and the forms appear on them as well. I need to do it this way since the forms + tabs are created at run-time.

But here's my question: There's a close button on the form, which frees the form's resources when clicked. But I also want the TAB to get closed when the form's button is clicked.

How do I get around this?

Thanks!


Solution

  • I don't like things getting to complicated

    How to get tabbed forms (PageControl)

    TForm1 = class( TForm )
      PageControl1 : TPageControl;
    
      procedure NewTabbedForm;
    end;
    
    procedure TForm1.NewTabbedForm;
    var
      LForm : TForm;
    begin
      // Some code to get a new form instance into LForm
    
      LForm := TTabForm.Create( Self );
    
      // now the magic to put this form into PageControl as a TabSheet
      LForm.ManualDock( PageControl1, PageControl1, alClient );
      // Finally
      LForm.Show;
    end;
    

    The Caption of the form will be automatically used for the automatically created TabSheet Caption.

    How to free/remove a tabbed form

    short and simple

    TTabForm = class( TForm )
      Close_Button : TButton;
      procedure Close_ButtonClick( Sender : TObject );
    end;
    
    procedure TTabForm.Close_ButtonClick( Sender : TObject );
    begin
      Self.Release;
    end;
    

    a little bit more

    TTabForm = class( TForm )
      Close_Button : TButton;
      procedure Close_ButtonClick( Sender : TObject );
      procedure FormClose( Sender : TObject; var Action : TCloseAction );
    end;
    
    procedure TTabForm.Close_ButtonClick( Sender : TObject );
    begin
      Self.Close;
    end;
    
    procedure TTabForm.FormClose( Sender : TObject; var Action : TCloseAction );
    begin
      Action := caFree;
    end;