等待WebBrowser加载计时器

时间:2012-08-24 13:14:32

标签: c# winforms browser

我正在创建一个简单的自动冲浪应用程序来学习WebBrowser对象。

我有一个23个URL的列表,我每隔几秒就会冲浪一次。

该应用很简单,转到论坛并打开FORM以添加新消息(不发送) 并继续前进,直到你到达列表的末尾。

我的问题是代码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++;          
    }

(对不起我的英文)

3 个答案:

答案 0 :(得分:1)

添加此类活动

You could disable your timer in your Time_tick function, 

timer1.Enabled = false;

然后在doc completed事件中重新启用它:

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

答案 1 :(得分: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();
    }
}

答案 2 :(得分:0)

//我在21岁开始进行更快的测试。 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++;          
}
timmer coad就是这个