C#等待浏览器加载芬兰然后启动计时器

时间:2016-09-18 15:41:26

标签: c# multithreading winforms

所以我长期以来一直在努力解决这个问题。我试图找出如何启用计时器并在网页加载完成后将其间隔设置为1000?

这是我到目前为止尝试过的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.Navigate("website.com");
            webBrowser1.ScriptErrorsSuppressed = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("brukernavn")[0].SetAttribute("value", textBox1.Text);
            webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("passord")[0].SetAttribute("value", textBox2.Text);
            webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("login_buton")[0].InvokeMember("click");
            timer1.Enabled = true;
            timer1.Interval = 7000;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            webBrowser1.Navigate("website.com/mygambling.php");
//Here i need a code to enable timer2 whit interval 1000 when the website is finnished loading
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("bet")[0].SetAttribute("value", 250);
            webBrowser1.Document.GetElementsByTagName("input").GetElementsByName("start")[0].InvokeMember("click");
        }
    }
}

所以我的问题是如何在页面加载完成后启用timer2并将timer2间隔设置为1000?

1 个答案:

答案 0 :(得分:4)

您已经知道如何启用计时器。 webbrowser有一个DocumentCompleted事件,您可以在其中订阅。这将帮助您确定何时完成页面加载:

private void timer1_Tick(object sender, EventArgs e)
{
    webBrowser1.Navigate("website.com/mygambling.php");
    webBrowser1.DocumentCompleted += DocumentCompleted;
}

private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.DocumentCompleted -= DocumentCompleted;
    timer2.Enabled = true;
}