Delphi – How to attach an event to IHTMLDocument2 link elements in Delphi

delphieventsihtmldocument2iwebbrowser2onclick

I'm using this code to get all the links from an IHTMLDocument2:

procedure DoDocumentComplete(const pDisp: IDispatch; var URL: OleVariant);
var
  Document:IHTMLDocument2;
  Body:IHTMLElement;
  Links:IHTMLElementCollection;
  i:integer;
  tmp:IHTMLElement;
begin
  try
  Document := (pDisp as  IWebbrowser2).Document AS IHTMLDocument2;
  Body := Document.body;
  Links := Document.links;
  for i := 0 to (Links.length-1) do
    begin
      tmp := (Links.item(i, 0) as IHTMLElement);
      //tmp.onclick := HOW SHOULD I ADD THE CALLBACK HERE?
      //ShowMessage(tmp.innerText);
    end;
  except
    on E : Exception do
      ShowMessage(E.ClassName+' error raised, with message : '+E.Message);
  end;
end;

How could I attach a function/procedure to .onclick to do a simple task like show an alert with the anchor text when the link is clicked?

Best Solution

One way is to sink events from the TWebBrowser with an object which implements IDispatch (like http://groups.google.com/group/borland.public.delphi.oleautomation/msg/a57d99e0e52c78ce)

you would set

tmp.onclick := TEventObject.Create(callbackProcedure) as IDispatch;