使用mshtml为页面中的超级链接添加Click事件
在使用mshtml操作HTML页面时可能遇到要为页面的超级链接添加Click事件的操作,可以用下面的代码来完成:
foreach(mshtml.IHTMLElement2 eleLink in this.doc.all)
{
if (eleLink.GetType().ToString() == "mshtml.HTMLAnchorElementClass")
{
((mshtml.HTMLAnchorEvents2_Event)eleLink).onclick += new mshtml.HTMLAnchorEvents2_onclickEventHandler(this.AnchorClick);
((mshtml.HTMLAnchorElementClass)eleLink).href = "#";
}
}
private bool AnchorClick(mshtml.IHTMLEventObj pEvtObj)
{
//添加单击超级链接的处理逻辑
//可以使用((mshtml.HTMLAnchorElementClass)(((mshtml.IHTMLElement)(((mshtml.IHTMLElement)(pEvtObj.srcElement)).parentElement))))获得被单击的超级链接并进一步获得其href等相关属性
}
{
if (eleLink.GetType().ToString() == "mshtml.HTMLAnchorElementClass")
{
((mshtml.HTMLAnchorEvents2_Event)eleLink).onclick += new mshtml.HTMLAnchorEvents2_onclickEventHandler(this.AnchorClick);
((mshtml.HTMLAnchorElementClass)eleLink).href = "#";
}
}
private bool AnchorClick(mshtml.IHTMLEventObj pEvtObj)
{
//添加单击超级链接的处理逻辑
//可以使用((mshtml.HTMLAnchorElementClass)(((mshtml.IHTMLElement)(((mshtml.IHTMLElement)(pEvtObj.srcElement)).parentElement))))获得被单击的超级链接并进一步获得其href等相关属性
}
Life is like a boat, and I'm at sea.