there are buttons on the site that the browser constantly presses, every 5 seconds the page loads and new buttons appear with the same name, the question is how to make the timer invoke the button every 5 seconds to click a button? Here's how:

private void button1_Click(object sender, EventArgs e) { System.Timers.Timer myTimer = new System.Timers.Timer(4000); myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed); myTimer.Start(); } void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { HtmlElementCollection elmCol = webBrowser1.Document.GetElementsByTagName("span"); //исключение тут foreach (HtmlElement elmBtn in elmCol) { if (elmBtn.GetAttribute("className") == "button-text follow-text") { elmBtn.Focus(); elmBtn.InvokeMember("Click"); } } } 

but throws an exception: System.InvalidCastException . Without a timer, the buttons are pressed perfectly, the click code is correct

  • There is a suspicion that the page does not have time to load, or the method called by the timer refers to the wrong page. - newman
  • Well, I'm waiting until the page is fully loaded and only then I press the button that the method should call - inkorpus
  • one
    Give stacktrace exceptions. Which object is reduced to what type? - VladD
  • And why do you have a timer System.Timers.Timer myTimer declared as a local variable? - Alexsandr Ter
  • one
    I would advise you to use the timer from the WinForms library , in order not to catch problems with multithreading. - Pavel Mayorov

2 answers 2

I advise you to use the timer from the Threading space.

  System.Threading.Timer service = new System.Threading.Timer(Update, null, 0, 5000); ..... private void Update(object obj) { ..... } 
  • In this case, there will be problems with the flows ... - Pavel Mayorov
  void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Action action = () => { HtmlElementCollection elmCol = webBrowser1.Document.GetElementsByTagName("span"); //исключение тут foreach (HtmlElement elmBtn in elmCol) { if (elmBtn.GetAttribute("className") == "button-text follow-text") { elmBtn.Focus(); elmBtn.InvokeMember("Click"); } } }; webBrowser1.Invoke(action); }