C# 如何捕获Web浏览器控件中任何按钮的点击事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14933979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:28:39  来源:igfitidea点击:

How to capture click event for any button inside in web browser control?

c#webbrowser-control

提问by Thomas

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.

假设我的 Web 浏览器显示一个 html 页面,其中有许多按钮。我只是想知道如何从我的 c# win 应用程序中捕获对 Web 浏览器控件内任何按钮的点击。

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.

如果可能,那么我想从该事件中捕获按钮名称、高度和宽度以及任何自定义属性。等请指导我。

采纳答案by AlphaOmega

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

你能告诉我如何读取 Web 浏览器控件中加载的任何 html 元素的自定义属性。谢谢

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:

如果您不想链接到“Microsoft.mshtml”,您可以尝试使用此示例方法。但是您无法通过反射读取所有成员:

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;
}