I got a VERY weird problem happening with ALL my DocumentCompleteEventHandlers.
Say I have a very simple handler:
void Download_Complete_Handler(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string link = webBrowser1.Url.ToString();
Regex rgx = new Regex("(^https://mysite.com/)");
if (rgx.IsMatch(link)) // have made it this way so that I don't remove the handler for every page. Pretty handy.
{
string name = choosename(); // my custom function to create new name
string surname = choosesurname(); // my custom function to create new surname
Random rand = new Random();
webBrowser1.Document.GetElementById("id").Focus();
SendKeys.SendWait(name + "." + surname + rand.Next(0, 9999).ToString());
name = "";
surname = "";
}
}
And I call this handler in following function which is called on button click:
void myfunction()
{
try
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Download_Complete_Handler);
webBrowser1.Navigate("mysite.com");
}
catch(Exception ex)
{
log(ex);// my custom log function
}
}
Now, when I first launch the program, and I click the button to trigger the handler, all works OK: Webbrowser is navigated, once page is loaded – the needed field is filled in.
Now let’s say, I click the same button once again, so that all process starts all over again. This time the handler is called twice: once page is loaded, the field is filled two times. Third click will trigger the handler three times, etc.
Do you know what I’m doing wrong?
Yes – you’re adding a new handler every time the button is clicked. The old handlers aren’t removed – they’ll stick around forever (unless you remove them explicitly, of course).
Add the handler once, and then just perform navigation in the button click.
As an aside, it’s generally not a good idea to create multiple instances of
Randomlike this. See my article on the topic.