Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

c# - Using WebBrowser in a console application

I want to use it to invoke some JS scripts on the webpage. I have this:

    static void Stuff()
    {
        WebBrowser browser = new WebBrowser();
        browser.Navigate("http://www.iana.org/domains/example/");
        HtmlDocument doc = browser.Document;
        //doc.InvokeScript("someScript");
        Console.WriteLine(doc.ToString());
    }

    static void Main(string[] args)
    {
        Console.WriteLine("hi");
        var t = new Thread(Stuff);
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

Question 1: I get an "object reference not set" exception when I try to get doc.ToString(). Why?

Question 2: How do I get some data from the HTML document into the main program? WebBrowser requires a separate thread, which requires a static method which can't return any value. How do I return, say, doc to the Main() so I can do something with it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Right idea, wrong execution. The WebBrowser.Navigate() only tells the web browser to start navigating to the web page you asked for. That takes time, hundreds of milliseconds typically. Internet Explorer internally starts threads to get the job done. It tells you when it is done by raising the DocumentCompleted event. You don't wait for that so that's crash city first.

Next problem is that the DocumentCompleted event won't be raised in your code. You have to honor the STA contract, it requires you to pump a message loop. That's the all-mighty way that a background thread, like the one that IE uses to retrieve a web page, tells your thread that the job is done.

The boilerplate code you need is available in this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...