【问题标题】:Create Form and WebBrowser at runtime在运行时创建表单和 WebBrowser
【发布时间】:2020-11-13 19:01:27
【问题描述】:

我正在使用 Delphi 7 并尝试在运行时在 Form 内创建 WebBrowser,但无法使其工作。代码如下:

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;

结果就像 WebBrowser 没有响应。我得到一个白屏并且没有错误消息。

请问,我错过了什么?谢谢!

【问题讨论】:

  • 表单以Form.ShowModal 显示,并一直等到它关闭才能在您的代码中继续,这样您就不会在表单可见时导航到任何地方。

标签: delphi delphi-7 twebbrowser


【解决方案1】:

您正在使用其ShowModal() 方法显示表单,该方法是一个同步(也称为阻塞)函数,在表单关闭之前不会退出。因此,当表单打开时,您永远无法拨打Navigate() 的电话。

你有两个选择:

  • 使用Show() 而不是ShowModal()Show() 向表单发出信号以显示自身,然后立即退出,从而允许后续代码在表单打开时运行。因此,您将不得不摆脱try...finally,而是使用表单的OnClose 事件在表单关闭时释放它,例如:
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(),请将对Navigate() 的调用移至Form 的OnShowOnActivate 事件中,例如:
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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2010-11-14
    • 2019-10-31
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多