WPF WebBrowser:如何设置元素单击事件?

发布于 2024-10-12 03:51:46 字数 521 浏览 1 评论 0原文

我已经弄清楚如何在页面加载完成后立即将所有内容变为红色:

private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
    var doc = (IHTMLDocument2)webBrowser1.Document;
    foreach (IHTMLElement elem in doc.all)
    {
        elem.style.backgroundColor = "#ff0000";
    }
}

现在,如果我想让元素仅在单击时改变颜色怎么办?我看到 elem 有一个 onclick 属性,但它的类型是 dynamic 所以我不知道如何处理它。 文档毫无用处。

I've figured out how to make everything red as soon as the page is finished loading:

private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
    var doc = (IHTMLDocument2)webBrowser1.Document;
    foreach (IHTMLElement elem in doc.all)
    {
        elem.style.backgroundColor = "#ff0000";
    }
}

Now what if I want to make the element only change color when it's clicked? I see that elem has an onclick property, but it's type is dynamic so I don't know what to do with it. The documentation is pretty useless.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝天 2024-10-19 03:51:46

您可以使用 HTMLDocumentClass 而不是 IHTMLDocument2 接口来实现这一点:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
    {
        mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)webBrowser1.Document;
        doc.HTMLDocumentEvents_Event_onclick += new mshtml.HTMLDocumentEvents_onclickEventHandler(OnClickHandler);
    }

    bool OnClickHandler()
    {
        mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)webBrowser1.Document;
        mshtml.IHTMLWindow2 win = doc.parentWindow;
        [email protected] = "#ff0000";
        return false;
    }

}

上述解决方案有一个缺点:onclick 事件不会冒泡,即使返回false(即单击超链接不会导航到其他页面)。

You could do it by using the HTMLDocumentClass instead of the IHTMLDocument2 interface:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
    {
        mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)webBrowser1.Document;
        doc.HTMLDocumentEvents_Event_onclick += new mshtml.HTMLDocumentEvents_onclickEventHandler(OnClickHandler);
    }

    bool OnClickHandler()
    {
        mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)webBrowser1.Document;
        mshtml.IHTMLWindow2 win = doc.parentWindow;
        [email protected] = "#ff0000";
        return false;
    }

}

The above solution, has one drawback: the onclick event does not bubble, even though false is returned (i.e. clicking at hyperlinks does not navigate to other pages).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文