Search code examples
delphidelphi-xe2

How refer to a particular instance of twebbrowser? - Delphi


If I create n Tabsheets at runtime and create one Webbrowser inside each tabsheet using a method such as:

        procedure createTab;
        var crm: TWebbrowser;
        var  ts: TsTabSheet;
        begin
        
       //Instance of tabsheet
       ts             :=  TsTabSheet.Create(pageControl);
       ts.PageControl :=  pageControl;
        
       //Instance of webbrowser          
       crm                   :=  TWebbrowser.Create(ts);
       crm.Parent            :=  TWinControl(ts);
       crm.Align             :=  alClient;
       end;

When one of tabsheet instance is active how could I know which webbrowser is inside it? Sample:

  procedure navigateToActiveTabsheet(url: string);
          begin
           //TO DO - How navigate to webbrowser inside active tabsheet?
          end;

Solution

  • The Controls property of a windowed control allows you to obtain every child control. Because these children can be any TControl descendent, you'll need to cast to TWebBrowser. Use the as operator to benefit from runtime validity checking of the cast:

    procedure navigateToActiveTabsheet(url: string); 
    var
      wb: TWebBrowser;
    begin    
      wb := pageControl.ActivePage.Controls[0] as TWebBrowser;
      wb.Navigate(url);
    end;