Link to home
Create AccountLog in
Avatar of AdrianSmithUK
AdrianSmithUK

asked on

C# webBrowser: How to add load event at runtime.

I would like to create a web browser object at runtime.

I don’t intend to display the object. I just want to query the DOM and then destroy the object.

How would I add an event listener that called a function at runtime.

Is that possible?

Kind Regards,


public partial class Form1 : Form
{
	public Form1()
	{
		InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
		WebBrowser wb1 = new WebBrowser();
		wb1.Navigate(new Uri("http://www.google.com"));
	}
}

Open in new window

Avatar of DjDezmond
DjDezmond
Flag of United Kingdom of Great Britain and Northern Ireland image

Well the code you've shown would work (as far as I know). The control wont appear on the form unless you add it to the control collection of the form. But will still actually load the specified URL into its frame, thus behaving as normal.

 
WebBrowser aTest = new WebBrowser();
            this.Controls.Add(aTest);
            aTest.Navigate("www.google.co.uk");

Open in new window


The question is, why are you trying to do this? What are you trying to achieve?
SOLUTION
Avatar of _valkyrie_
_valkyrie_
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of AdrianSmithUK
AdrianSmithUK

ASKER

Many thanks for the solutions gentlemen.

DjDezmond: I tested your solution and it works very nicely.
 
Valkyrie: I tried the code below but it didn't fire the onload event. Any ideas why?  Is it because you used a different event type? I'll wait for your answer and then I'll close the question down and split the final solution between you?

Kind Regards,

Adrian




public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WebBrowser wb1 = new WebBrowser();
            wb1.LocationChanged += new EventHandler(wb1_LocationChanged);
            wb1.Navigate(new Uri("http://www.google.com"));
        }

        void wb1_LocationChanged(object sender, EventArgs e)
        {
            MessageBox.Show("Loaded");
        } 
    }

Open in new window

It's because I used a different event, DjDezmond used the event you're looking for.
Many thanks gentlemen.