2012-08-24 86 views
0

我正在創建一個簡單的自動衝浪應用來學習WebBrowser對象。等待WebBrowser加載定時器

我有一個列表,我每衝浪幾秒鐘就有23個網址。

該應用程序很簡單,去論壇,並打開表格添加新消息(不發送它) 並繼續前進,直到你到達列表的末尾。

我的問題是代碼forumAction.FillOutFormIn(webBrowser1.Document);在錯誤的站點執行。

我認爲這是因爲文檔沒有準備好。

那麼有沒有辦法停止計時器,直到文檔準備就緒?

這裏是TIMER TICK功能:

//I start is in 21 for faster testing. 
int timesToRun = 21; 
    private void Time_Tick(object sender, EventArgs e) 
    { 

      Console.WriteLine(timesToRun.ToString()); 
      string currentSite = siteList.GetSiteFromIndex(timesToRun); 

      webBrowser1.Document.Window.Navigate(currentSite); 

      //I think I need to wait here until the document is ready 

      //this line of code doesn't run on timeToRun = 22 
      forumAction.FillOutFormIn(webBrowser1.Document); 

      Console.WriteLine(webBrowser1.Url); 
      timerLabel1.Text = siteList.SiteLists.Count + ">" + timesToRun + ""; 

      if (timesToRun >= siteList.SiteLists.Count - 1) 
      { 
       enableControls(true); 
       timesToRun = 0; 
       timer.Stop(); 
       Console.WriteLine("done"); 

      } 

      timesToRun++;   
    } 

(對不起,我的英語)

回答

1

您可以簡單地編寫控件的DocumentCompleted事件。

這將允許您在加載頁面時重新啓動計時器。

webBrowser1.Navigated += WebBrowser_DocumentCompleted; 
timesToRun = 22; 

private void Time_Tick(object sender, EventArgs e) 
{ 
    timer.stop(); 
    webBrowser1.Document.Window.Navigate(url); 
} 

void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    timesToRun--; 
    if(timesToRun > 0) 
    { 
     timer.Start(); 
    } 
} 
+0

這項工作,但當它結束計時器重新開始,即使我說(當timesToRun是23)設置timesToRun爲0,並停止計時器 – samy

+0

我添加了一個解決方案,我的代碼。 –

1

添加事件這樣

You could disable your timer in your Time_tick function, 

timer1.Enabled = false; 

然後在文檔完成的事件重新啓用它:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    if(timesToRun > 0) 
    { 
     timer1.Enabled = true; 
    } 
} 
+0

這項工作,但是當它到達終點計時器重新開始甚至afther我說(當timesToRun爲23)將timesToRun設置爲0並停止計時器。 – samy

+0

如果我理解你的話,上面的編輯可能會有所幫助。 –

0

//我開始是在21更快的測試。 int timesToRun = 21; 私人無效Time_Tick(對象發件人,EventArgs的) {

 Console.WriteLine(timesToRun.ToString()); 
     string currentSite = siteList.GetSiteFromIndex(timesToRun); 

     webBrowser1.Document.Window.Navigate(currentSite); 

     //I think I need to wait here until the document is ready 

     //this line of code doesn't run on timeToRun = 22 
     forumAction.FillOutFormIn(webBrowser1.Document); 

     Console.WriteLine(webBrowser1.Url); 
     timerLabel1.Text = siteList.SiteLists.Count + ">" + timesToRun + ""; 

     if (timesToRun >= siteList.SiteLists.Count - 1) 
     { 
      enableControls(true); 
      timesToRun = 0; 
      timer.Stop(); 
      Console.WriteLine("done"); 

     } 

     timesToRun++;   
} 

的蒂莫COAD isthis