WebBrowser Control in a new thread

前端 未结 4 1439
执笔经年
执笔经年 2020-11-21 06:24

I have a list Uri\'s that I want \"clicked\" To achieve this I\"m trying to create a new web-browser control per Uri. I create a new thread per Uri. The problem I\'m having

4条回答
  •  走了就别回头了
    2020-11-21 06:54

    You have to create an STA thread that pumps a message loop. That's the only hospitable environment for an ActiveX component like WebBrowser. You won't get the DocumentCompleted event otherwise. Some sample code:

    private void runBrowserThread(Uri url) {
        var th = new Thread(() => {
            var br = new WebBrowser();
            br.DocumentCompleted += browser_DocumentCompleted;
            br.Navigate(url);
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }
    
    void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
        var br = sender as WebBrowser;
        if (br.Url == e.Url) {
            Console.WriteLine("Natigated to {0}", e.Url);
            Application.ExitThread();   // Stops the thread
        }
    }
    

提交回复
热议问题