views:

176

answers:

1

I want my BHO to listen to onmousedown event of some element in a certain webpage. I have all the code that find the specific element, and in msdn its says that I need to use the get_onmousedown event. I came up with this code.

 CComQIPtr<IHTMLElement> someElement;
 VARIANT mouse_eve;
 someElement->get_onmousedown(&mouse_eve);

The question is, how do I tell it to run some function when this event occurs?

+2  A: 

v - VARIANT of type VT_DISPATCH that specifies the IDispatch interface of an object with a default method that is invoked when the event occurs.

Event handlers in this context are COM instances that implement IDispatch - so you need to pass a pointer to an IDispatch that your event handler object implements:

CComQIPtr<IDispatch> spDisp(spMyHandler); // something like that
someElement->put_onmousedown(CComVariant(spDisp));

Note: put_ instead of get_ - you want to register a handler.

On this, IDispatch::Invoke() gets called with:

  • wFlags containing DISPATCH_METHOD ("a method is getting invoked")
  • dispIdMember being 0 / DISPID_VALUE ("the default method")

Put together this should become something like:

HRESULT MyHandler::Invoke(DISPID dispIdMember, REFIID, LCID, WORD wFlags, 
                          DISPPARAMS*, VARIANT*, EXCEPINFO*, UINT*)
{
    // ...

    if((wFlags & DISPATCH_METHOD) && (dispIdMember == DISPID_VALUE)) 
    {
        // ...
    }
}
Georg Fritzsche
it doesn't let me to add "MainClassName::Invoke" as a function: "overriding virtual function differs from 'ATL::IDispatchImpl<T,piid,plibid,wMajor,wMinor>::Invoke' only by calling convention"
shaimagz
Use `HRESULT STDMETHODCALLTYPE Invoke(/* params */)` or `STDMETHOD(Invoke)(/* params */)` for the declaration.
Georg Fritzsche
Thank you! one last question: in the invoke method, how do I use the current IDispatch?
shaimagz
I think I understand, but the only reason I wanted the mouse event is to get the changes on the page when someone clicks on something. and I need to get an IHTMLDocument2 object.
shaimagz
I see, i somehow saw a different question there. But you can always register custom event listener objects that have access to the document you need?
Georg Fritzsche