Internet Explorer を使用して、人がテキストをクリックした位置を取得したいと思います。3~4文字の誤差は問題ありません。テキストは編集できず、通常はスパン要素にあります。
HTMLDocument のクリック イベント リスナーを設定できることは承知していますが、常に HTMLDocument オブジェクトを持っているとは限らないため、イベントを見逃す可能性があります。
IHTMLSelectionObject を取得してから、IHTMLTxtRange でテキスト範囲を作成しようとしましたが、少なくとも 1 文字が選択されているのではなく Web ページが単にクリックされた場合、IHTMLTxtRange にはクリックされた要素ではなく、HTMLBody の親があります。 .
HTMLDocument.activeElement も信頼できません。私のテストでは、クリックされた要素を実際に返すことはありません。通常、ツリーのどこかにある要素の主要な親を返します。
MSHTML を使用してこれを達成する別の方法はありますか?
WIN API GetCursorPos も使用してみましたが、この位置をどうするかわかりません。これを実際の要素に変換する方法がわかりません。
編集: 私も面白いアイデアを考えました。カーソルのある要素を知る必要がある場合は、ドキュメント全体に mouseDown またはクリック イベントを設定します。次に、自分のクリックを発生させ、イベントをキャッチします。イベントの IHTMLEventObj には、カーソルの場所を教えてくれると思っていた FromElement があります。mouseDown および click イベントでは常に何もないようです。私にとって、少なくともこのオブジェクトは、マウスオーバー イベントなどでのみ使用されます。
以下は、少なくともキャラクターが選択されたときに私が持っているものです。
Private Function GetHTMLSelection(ByVal aDoc As IHTMLDocument2, ByRef htmlText As String) As Integer
Dim sel As IHTMLSelectionObject = Nothing
Dim selectionRange As IHTMLTxtRange = Nothing
Dim rangeParent As IHTMLElement4 = Nothing
Dim duplicateRange As IHTMLTxtRange = Nothing
Dim i As Integer
Dim x As Integer
Dim found As Boolean
Try
'get a selection
sel = TryCast(aDoc.selection, IHTMLSelectionObject)
If sel Is Nothing Then
Return -1
End If
'the range of the selection.
selectionRange = TryCast(sel.createRange, IHTMLTxtRange)
If selectionRange Is Nothing Then
Return -1
End If
'the the parent element of the range.
rangeParent = TryCast(selectionRange.parentElement, IHTMLElement4)
'duplicate our range so we can manipulate it.
duplicateRange = TryCast(selectionRange.duplicate, IHTMLTxtRange)
'make the dulicate range the whole element text.
duplicateRange.moveToElementText(rangeParent)
'get the length of the whole text
i = duplicateRange.text.Length
For x = 1 To i
duplicateRange.moveStart("character", 1)
If duplicateRange.compareEndPoints("StartToStart", selectionRange) = 0 Then
found = True
Exit For
End If
Next
If found Then
Debug.Print("Position is: " + x.ToString)
htmlText = duplicateRange.text
Return x
Else
Return -1
End If
Catch ex As Exception
Return -1
Finally
End Try
End Function