How to capture click event for any button inside i

2019-01-15 04:40发布

问题:

Suppose my web browser is showing a html page where many buttons are there. I just like to know how could I capture click on any button inside web browser control from my c# win apps.

If it is possible then from that event i want to capture button name,height and width and any custom property. etc. Please guide me.

回答1:

This will be helpful if you want to capture only mouse clicks:

WebBrowser _browser;
this._browser.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
...
private void browser_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e)
{
    this._browser.Document.Body.MouseDown += new HtmlElementEventHandler(Body_MouseDown);
}
...
void Body_MouseDown(Object sender, HtmlElementEventArgs e)
{
    switch(e.MouseButtonsPressed)
    {
    case MouseButtons.Left:
        HtmlElement element = this._browser.Document.GetElementFromPoint(e.ClientMousePosition);
        if(element != null && "submit".Equals(element.GetAttribute("type"),StringComparison.OrdinalIgnoreCase)
        {
        }
    break;
    }
}

can u please tell me how can i read custom attribute of any html element loaded inside web browser control. thanks

If You don't want to link to "Microsoft.mshtml", You can try to use this sample method. But you can't read all members thru reflection:

public static String GetElementPropertyValue(HtmlElement element, String property)
{
    if(element == null)
        throw new ArgumentNullException("element");
    if(String.IsNullOrEmpty(property))
        throw new ArgumentNullException("property");

    String result = element.GetAttribute(property);
    if(String.IsNullOrEmpty(result))
    {//В MSIE 9 получить свойство через DomElement не получается. Т.к. там он ComObject.
        var objProperty = element.DomElement.GetType().GetProperty(property);
        if(objProperty != null)
        {
            Object value = objProperty.GetValue(element.DomElement, null);
            result = value == null ? String.Empty : value.ToString();
        }
    }
    return result;
}