繁体   English   中英

WebBroswer不触发DocumentCompleted事件

[英]WebBroswer not firing DocumentCompleted event

我正在尝试使用WebBrowser因为我需要与通过JS创建并且未出现在原始响应中的某些元素进行交互。

我已经阅读了其他问题,因为单线程程序正在等待读取键或类似的操作,因此无法触发该事件,因此不会触发该事件。

但是,就我而言,这只是在完成程序,从未输入Client_DocumentCompleted方法。

[STAThread]
static void Main(string[] args)
{
    Helper();
}

static void Helper()
{

    WebBrowser client = new WebBrowser();
    client.DocumentCompleted += Client_DocumentCompleted;
    client.AllowNavigation = true;
    client.Navigate("https://www.google.com/");
}

private static void Client_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser client = (WebBrowser)sender;
    while (client.ReadyState != WebBrowserReadyState.Complete)
    {
        Console.WriteLine(client.ReadyState);
    }
    string htmlCode = client.Document.ToString();
    Console.Write(htmlCode);

    Console.ReadKey();
}

我尝试在单独的线程中进行WebBrowser交互没有成功。

var t = new Thread(Helper);
t.SetApartmentState(ApartmentState.STA);
t.Start();

编辑:更新为包括我的解决方案中已经存在的[STAThread]属性

您应该将STAThread属性添加到Main

[STAThread]
static void Main(string[] args)
{
    //...
}

使用COM组件时这是必需的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM