在控制台应用程序中使用web浏览器 [英] Using WebBrowser in a console application

查看:418
本文介绍了在控制台应用程序中使用web浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用它来调用网页上的一些JS脚本。我有这样的:

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();
    }



问题1:我得到一个对象引用未设置异常,当我尝试要获得 doc.ToString()。为什么

问题2:我如何从HTML文档中一些数据主程序? web浏览器需要一个单独的线程,这就要求不能返回任何值的静态方法。我如何返回,说,商务部的Main(),所以我可以用它做什么?

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?

推荐答案

正确的想法,错执行。该WebBrowser.Navigate()只告诉web浏览器的启动的导航到该网页,你提出的要求。这需要时间,几百毫秒通常的。 Internet Explorer的内部启动线程来完成这项工作。它会告诉你,当它是通过提高DocumentCompleted事件完成。你不等待,这样的暴跌城市第一位。

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.

接下来的问题是,DocumentCompleted事件不会在你的代码得到提升。你必须履行合同STA,它需要你抽消息循环。这就是万能的方式,后台线程,就像IE浏览器用来检索网页的人,讲述的的线程任务完成。

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.

这篇关于在控制台应用程序中使用web浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆