The task is to click on a button in the application to select the parameters in the two combo boxes on the site and press the button there.
Here is the code:

HtmlWindow frames = webBrowser1.Document.Window.Frames[0]; var elements = frames.Document.GetElementsByTagName("select"); elements[0].SetAttribute("value", "1"); elements[1].SetAttribute("value", "1"); var elements1 = frames.Document.GetElementsByTagName("input"); elements1[0].InvokeMember("click"); 

Everything works smoothly, I press the button in the application, everything that needs to be done on the site, very quickly I press a button (by hand) quickly and everything happens on the site. But as soon as I insert the code into the loop, the application immediately hangs after clicking on the button.

The condition for exit from the cycle is 100%. For the test, I tried even through for to put 2-3 passes through the cycle, no more, it still hangs. I suspect that the site does not have time to respond to the code that is in the loop. How can this be prevented? If you use webBrowser1.DocumentCompleted , what will the handler look like? After all, I work in a cycle. If it had to be done once, then without problems, but with a cycle, problems arise.

  • Show your cycle - Sergej Loos
  • Well, let's say the above described code will be in a for loop (int i = 0; i <5; i ++). Already in this cycle, the application freezes. - Pyrejkee

2 answers 2

It may be necessary to let the browser handle its events. To do this, use Application.DoEvents (). As an idea:

  for (...) { // событие, которое должно срабатывать после вашей обработки документа // я использовал DocumentCompleted, но у вас может быть другое bool loaded = false; webBrowser.DocumentCompleted += (x, y) => { loaded = true; }; // ваши операции .. с документом // здесь ждем окончания операции примерно 10 секунд int waitCount = 0; Application.DoEvents(); // !!! while (loaded == false) { Thread.Sleep(200); Application.DoEvents(); // !!! waitCount++; if (waitCount * 50 >= 10000 /*ca. 10 sec*/ ) throw new Exception("timeout"); } } 
  • Is it possible to do this somehow without thread.sleep? After all, everyone has the speed of the Internet and the workload of the PC at the time of the operation is different ... Someone needs 200 milliseconds, some more - Pyrejkee
  • I tested it, the code works like a watch, but I would like to avoid using Thread.Sleep (); If it is possible, please tell me. - Pyrejkee
  1. The page is loaded in the UI stream.
  2. You access the document after the transition is initiated.
  • How do I fix the situation? - Pyrejkee