簡體   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