Image click in C# WinForms Browser Control

770 views Asked by At
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.Document.Body.MouseDown += Body_MouseDown;
}

void Body_MouseDown(object sender, HtmlElementEventArgs e)
{   
    switch (e.MouseButtonsPressed)
    {
        case MouseButtons.Left:
            HtmlElement element = webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition);
            if (element != null && "img".Equals(element.GetAttribute("type"), StringComparison.OrdinalIgnoreCase))
            {
                MessageBox.Show("Image Was Clicked");
            }
            break;
    }
}

This is the code I am using but it doesn't seem to work. What am I doing wrong? Is this the correct way?

Any & All Help Is Appreciated.

1

There are 1 answers

0
Yegor Korotetskiy On

Not all images in html has the type attribute. So you must define such that your clickable image has. For example, I redacted your code:

Initialisation of the webBrowser (you can put it in the constructor of your WinForm):

webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            webBrowser1.Navigate("http://www.google.com");

Your procedure Body_MouseDown:

void Body_MouseDown(object sender, HtmlElementEventArgs e)
            {
                switch (e.MouseButtonsPressed)
        {

            case MouseButtons.Left:
                HtmlElement element = webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition);
                if (element != null)
                {
                    string s = element.Style;

                    if ((s != null) && (s.IndexOf(".png") != -1)) MessageBox.Show("Image Was Clicked");
                }
                break;
        }       
            }

If you click on the google logo you will get the message box you want. The point is that I use attribute Style of the HtmlElement and searching the substring ".png" in it. You can search for all formats you want: jpg, gif, bmp, or all together. Good luck.