-1

When I call WebBrowser1.Navigate('www.google.com'); from a Button OnClick event, eg:

procedure TForm4.Button1Click(Sender:TObject);
begin
  WebBrowser1.Navigate('www.google.com');
end;

The web page shows up in WebBrowswer1.

But, if I make my own procedure, eg:

procedure MyProcedure;
var 
  WebBrowser1:TWebBrowser;
begin
  WebBrowser1.Navigate('www.google.com'); 
end;

And then try to call this procedure from a Button OnClick event, I get an Access Violation error.

Just wondering, why does it work when Delphi makes the procedure for me, but it doesn't work when I write the procedure myself? How can I correct this, or what code do I have to write in the procedure to make it work?

RRUZ
  • 134,889
  • 20
  • 356
  • 483
Peter James
  • 237
  • 1
  • 6
  • 18

1 Answers1

1

In the first excerpt you have added a TWebBrowser control to the form in the IDE designer. As such the VCL framework instantiates the control for you. Make it be a child control of the form, and applies all the steps needed to get the control up and running correctly.

In the second excerpt, there is no form, no control added in the designer. You declare a local variable WebBrowser1, which you do not initialise. No browser control is created, and any attempt to use the uninitialized variable WebBrowser1 leads to undefined behaviour. A runtime error is pretty much inevitable.

If you want to correct this you would need to instantiate an instance of the TWebBrowser control, set its parent appropriately, and take all the other steps that the VCL does for you.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490