0

How can I change this foreach loop into an if statement. It shows message for every image [EVEN IF I click on only one]. I only want to show a message on click of picture...

[code]

 private void webBrowser1_DocumentCompleted(object sender, CompletedEventArgs e)
        {
            foreach (HtmlElement ele in
                     webBrowser1.Document.GetElementsByTagName("img"))
            {
                ele.AttachEventHandler("onclick", Document_Click);
            }
        }

 private void Document_Click(object sender, EventArgs e)
        {
                MessageBox.Show("You clicked an image.");
        }

[what i've tried]

 if (webBrowser1.Document.GetType().GetElementType().Equals("img"))
 {
    // I tried this
 }

 HtmlElement elemz;
 if (elemz.GetAttribute("type").Equals("img"))   
 {
    // And this
 }

 HtmlElement elemz;
 if (elemz == webBrowser1.Document.GetElementsByTagName("img"))
 {
    // Also this
 }

 if (webBrowser1.Document.GetType("img") == true)
 {
    // Finally I tried this
 }

 HtmlElement elemz;
 if (elemz.GetAttribute("type") == webBrowser1.Document.GetElementsByTagName("img"))
 {
    // My last hope was this 
 }

1 Answers1

0

It's not that the click event is showing for every image, it's because the DocumentCompleted event is firing multiple times. (see WebBrowser DocumentCompleted event fired more than once). If you check e.Url to make sure you are only running your code for the actual page DocumentCompleted you'll see the event only fires once.

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
        if (e.Url.Equals(webBrowser1.Url)) {
            foreach (HtmlElement ele in webBrowser1.Document.GetElementsByTagName("img")) {

                ele.AttachEventHandler("onclick", Document_Click);
            }
        }
    }
Community
  • 1
  • 1
Eric Carlson
  • 761
  • 1
  • 6
  • 11