簡體   English   中英

無法等待使用WebBrowser控件加載網頁

[英]Unable waiting for web page loading using WebBrowser control

我正在編寫帶有本地站點網頁截圖的服務。 我正在使用WebBrowser控件將網頁捕獲為圖像。 以下是我正在使用的代碼:

 namespace MakeScreenShotURL { class Program { private static Config config = new Config(System.Reflection.Assembly.GetExecutingAssembly().Location); [STAThread] static void Main() { int width = 1700; int height = 1700; string username = "userdata"; string password = "passworddata"; int currentmonth = DateTime.Now.Month; int nextmonth = DateTime.Now.Month + 1; int year = DateTime.Now.Year; screen(width, height, year, nextmonth, currentmonth, username, password); } static void screen(int width, int height, int year, int nextmonth, int currentmonth, string username, string password) { string PlaceCode = config.GetAppSetting("place"); string[] Places = PlaceCode.Split(';'); //contains a list of sites for example: Berlin; Munich; Dresden foreach (string pl in Places) { using (WebBrowser browser = new WebBrowser()) { browser.Width = width; browser.Height = height; browser.ScrollBarsEnabled = true; Uri uri = new Uri(" http://localsite.php?y=" + year + "&m=" + nextmonth + "&p=" + pl + " "); string additionalHeaderInfo = "Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)) + System.Environment.NewLine; browser.Navigate(uri, null, null, additionalHeaderInfo); Wait(2); //waiting for pages to load 2 seconds using (Graphics graphics = browser.CreateGraphics()) using (Bitmap bitmap = new Bitmap(browser.Width, browser.Height, graphics)) { Rectangle bounds = new Rectangle(0, 0, bitmap.Width, bitmap.Height); browser.DrawToBitmap(bitmap, bounds); bitmap.Save("C:/Users/user/image/screenshot" + pl + ".jpeg", ImageFormat.Jpeg); } Application.Run(); } } Application.Exit(); } static void Wait(int number) { DateTime time = DateTime.Now; do { Application.DoEvents(); } while (time.AddSeconds(number) > DateTime.Now); } } } 

該程序從Places數組中創建第一個元素(柏林)的屏幕快照,並將其保存到磁盤。 但是,當從數組中選擇第二個元素時,程序將在執行之后掛起:

Application.Run();

該程序可能期望某些內容,但我無法理解。

有人可以幫我嗎?

事實確實如此,這讓我真的很感興趣,因為它沒有Web瀏覽器與之交互的父窗口和用戶界面。

無論如何,Application.Run()進入主消息循環,因此它等待消息。 此循環通常一直運行到被強制停止為止,例如通過發送WM_QUIT消息。

Application.DoEvents()做類似的事情,但是不會阻塞。 它只是在消息隊列內部查找,執行其中的所有消息,然后返回。 因此,您可以刪除對Application.Run()的調用。

如果要創建嚴肅的應用程序,則至少需要開始使用事件。 將方法附加到WebBrowser.DocumentCompleted,然后在那里等待頁面加載,然后運行對browser.DrawToBitmap的調用。

您還需要提供一種比DoEvents更好的執行消息的方法,因為當前的解決方案基本上將在加載瀏覽器時占用單個CPU內核。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM