Patric Nøis Patric Nøis - 2 months ago 22
C# Question

C# Wait for browser to finnish load then start a timer

So I have been struggling with this problem for long time now. I am trying to find out how I can enable a timer and set its interval to 1000 when the webpage is finished loading?

Here is the code I've tried with so far:

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");
}
}
}


So my question is how can I enable the timer2 and set timer2 interval to 1000 when the page is finished loading?

Answer

You already know how to enable timers. The webbrowser has a DocumentCompleted event where you can subscribe to. This will help you to determine when loading of the page has finished:

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;
}