Reputation: 31
I'm trying to connect to Internet Explorer and add listeners to any DOM event, including custom events. How can this be done? I'm trying this variant, but without any results:
//...
using mshtml;
using SHDocVw;
using System.Windows.Browser;
class Test {
public Test(){
IWebBrowser2 browser = BrowserHelper.GetBrowserInstance();
var a = browser.Document as HTMLDocument;
mydelegate obj = this.somefunction;
a.attachEvent("onclick", obj);
}
public delegate void mydelegate(object sender, HtmlEventArgs args);
public void somefunction(object sender, HtmlEventArgs args)
{
MessageBox.Show("Clicked!");
}
}
BrowserHelper returns correct browser instance.
Upvotes: 1
Views: 2360
Reputation: 42444
This works for me, without using SHDOCVW directly. I don't know a solution for getting the custom events from the DOM. If you know the list of custom events you want to listen for it can be done easily.
private void webBrowser1_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
// obtain HtmlDocument
HtmlDocument htmlDoc = webBrowser1.Document;
// loop over ALL elements in HtmlDoc
foreach(HtmlElement element in htmlDoc.All)
{
// for the HtmlElements type fetch its suported Events
// from the typeinfo
// we use a LinqQuery to filter in the future
var listOfEvents = from domInt in element.GetType().GetEvents()
// where domInt.Name.Contains("click")
select domInt;
// iterated over the EventMembers
foreach (var htmlevent in listOfEvents)
{
// invoke .Net managed AddEventHandler
htmlevent.AddEventHandler(
element,
new HtmlElementEventHandler(GenericDomEvent));
}
}
}
// do usefull stuff with the even raised
private void GenericDomEvent(object sender, HtmlElementEventArgs e)
{
Debug.WriteLine(e.EventType);
}
Upvotes: 4