I’m working on a project in which I’m writing a c# windows application that wants to get the current element under the cursor from a running instance of Internet Explorer.
I can get the handle of IHtmlDocument2 of the running instance of IE and I want to assign it the onmouseover event like this:
DHTMLEventHandler myHandler = new DHTMLEventHandler(htmlDocument);
myHandler.Handler += new DHTMLEvent(this.BrowserEventHandler);
htmlDocument.onmouseover = myHandler;
And because I didn’t want the IE to eat other events (a famous but solved question), I should create a DHTMLEventHandler class like this:
public delegate void DHTMLEvent(IHTMLEventObj obj);
[ComVisible(true)]
public class DHTMLEventHandler
{
public DHTMLEvent Handler;
private IHTMLDocument2 Document;
public DHTMLEventHandler(IHTMLDocument2 doc)
{
Document = doc;
}
[DispId(0)]
public void Call()
{
Handler(Document.parentWindow.@event);
}
}
And my BrowserEventHandler method is like this:
public void BrowserEventHandler(IHTMLEventObj e)
{
}
Still empty (but I want to get the element’s innerHtml under cursor), but still this method is empty and I get :
A first chance exception of type ‘System.InvalidCastException’ occurred in FindText.exe
Whenever I move the mouse.
Questions:
- Why I’m getting this exception?
- Is it possible to get e.srcElement.innerhtml in a variable and use in my c# application?
Let me know if there’s something unclear and ambiguous. Thanks in advance for any help and ideas. I greatly appreciate any comments and helps.
Update:
To answer my second question, it seems possible to get the e.srcElement.innerHTML of the IHTMLEventObj e but I really don’t know why the BrowserEventHandler method is never called. Any ideas or hints?
update2:
Ok, I found the problem. First I changed some settings of my project to get the line where the exception occurs first (since it’s a first chance exception) like this:
In visual studio: Menu >> Debug >> Exceptions >> CLR exceptions >> system and check the throw option of SystemInvalidCastException.
I found the problem is with this line of DHTMLEventHandler class:
Handler(Document.parentWindow.@event);
It throws Invalid Cast Exception which I think is related to Threads according to my recent searches.
I guess I should set ApartmentState to ApartmentState.STA. But I don’t know how. any ideas?
Ok,I found the solution! 🙂
I needed to change
DHTMLEventHandlerclass like this:But if anybody else tries to use my solution, I don’t know whether It has any side effects in other situations. At least it works fine for me! 🙂