TWebBrowser - Detecting the tag under caret

2019-07-25 12:58发布

问题:

I want to detect on which HTML tag (more exactly hyperlink) is the caret.

procedure THTMLEdit.ShowTag;     
var
  CursorPos: TPoint;
  HtmlElement: IHTMLElement;
  iHTMLDoc: IHtmlDocument2;
begin
 if Supports(wbBrowser.Document, IHtmlDocument2, iHTMLDoc) then
  begin
    if GetcaretPos(CursorPos) then
    begin
      CursorPos := wbBrowser.screentoclient(CursorPos);
      HtmlElement := iHTMLDoc.ElementFromPoint(CursorPos.X, CursorPos.Y);  // I NEED KEYBOARD CARET HERE, NOT MOUSE CURSOR
      if HtmlElement <> NIL
      then label1.Caption:= HtmlElement.tagName;
    end;
  end;
end;

Notes:
TWebBrowser is in DesignMode ( DesignMode := 'On' ).
TWebBrowser is in its own form at design time but at runtime is re-parented in another form (in a panel).

UPDATE:
The thing that I need is IHTMLTxtRange (I think). It works when I double click a link/word. But I don't know how to get the tag under caret when no text/link is selected.

回答1:

GetcaretPos(CursorPos) returns client (relative) coordinates (See GetCaretPos function)

Remove wbBrowser.screentoclient(CursorPos) and it should work fine. I have tested with your code sample above