I'm using Delphi 7 and trying to create a WebBrowser
inside a Form
, both at run time, but can't make it work. Here is the code:
procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm.Create(nil);
try
Form.Width := 500;
Form.Height := 500;
Form.BorderStyle := bsDialog;
Form.Position := poScreenCenter;
Form.Caption := 'Select the Option';
Brws := TWebBrowser.Create(Form);
Brws.ParentWindow := Form.Handle;
TWinControl(Brws).Parent := Form;
Brws.Align := alClient;
Brws.AddressBar := False;
Brws.MenuBar := False;
Brws.StatusBar := False;
Application.ProcessMessages;
if Form.ShowModal = mrOk then
Brws.Navigate('https://www.google.com');
finally
Form.Free;
end;
end;
The result is like WebBrowser is not responding. I got a white screen and no error messages.
Please, what am I missing? Thanks!
You are displaying the Form using its ShowModal()
method, which is a synchronous (aka blocking) function that does not exit until the Form is closed. So, you are never reaching the call to Navigate()
while the Form is open.
You have two options:
Show()
instead of ShowModal()
. Show()
signals the Form to display itself, and then exits immediately, allowing subsequent code to run while the Form is open. As such, you will have to get rid of the try...finally
and instead use the Form's OnClose
event to free the Form when it is closed, eg:procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm.Create(Self);
Form.Width := 500;
Form.Height := 500;
Form.BorderStyle := bsDialog;
Form.Position := poScreenCenter;
Form.Caption := 'Select the Option';
Form.OnClose := BrowserFormClosed;
Brws := TWebBrowser.Create(Form);
TWinControl(Brws).Parent := Form;
Brws.Align := alClient;
Brws.AddressBar := False;
Brws.MenuBar := False;
Brws.StatusBar := False;
Form.Show;
Brws.Navigate('https://www.google.com');
end;
procedure TForm1.BrowserFormClosed(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
ShowModal()
then move the call to Navigate()
into the Form's OnShow
or OnActivate
event instead, eg:procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm.Create(nil);
try
Form.Width := 500;
Form.Height := 500;
Form.BorderStyle := bsDialog;
Form.Position := poScreenCenter;
Form.Caption := 'Select the Option';
Form.OnShow := BrowserFormShown;
Brws := TWebBrowser.Create(Form);
TWinControl(Brws).Parent := Form;
Brws.Align := alClient;
Brws.AddressBar := False;
Brws.MenuBar := False;
Brws.StatusBar := False;
Form.ShowModal;
finally
Form.Free;
end;
end;
procedure TForm1.BrowserFormShown(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm(Sender);
Brws := TWebBrowser(Form.Components[0]);
Brws.Navigate('https://www.google.com');
end;