简体   繁体   中英

Image click in C# WinForms Browser Control

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM