-1
我需要找出在WebBrowser控件中選定文本的位置。我可以通過獲取IHTMLTxtRange相對於文本的位置
IHTMLDocument2 htmlDocument = BookReaderWeb.Document as IHTMLDocument2;
IMarkupServices ms = (IMarkupServices) htmlDocument;
IHTMLSelectionObject selection = htmlDocument.selection;
if (selection == null) return;
IHTMLTxtRange range = selection.createRange() as IHTMLTxtRange;
獲得IHTMLTxtRange,但我不知道如何獲取相對於全文(而不是HTML)範圍內的位置。 謝謝。
UPDATE
由於Noseratio建議,我實現了下面的代碼:
IHTMLDocument2 htmlDocument = BookReaderWeb.Document as IHTMLDocument2;
var str = htmlDocument.body.outerText;
IMarkupServices ms = (IMarkupServices) htmlDocument;
IHTMLSelectionObject selection = htmlDocument.selection;
if (selection == null) return;
IHTMLTxtRange range = selection.createRange() as IHTMLTxtRange;
dynamic body = htmlDocument.body;
var bodyRange = body.createTextRange();
bodyRange.moveToElementText(body);
var bodyText = bodyRange.text;
var counter = 0;
while (bodyRange.compareEndPoints("StartToStart", range) != 0)
{
bodyRange.moveStart("character", 1);
++counter;
}
MessageBox.Show(str.Substring(counter, 20));
,但它不會給正確的結果。該位置是幾個字符錯誤地向前,那麼它應該是。它只發生在大型HTML文件上,它可以在較小的文件上完美工作。看起來像dom api將某種標籤解釋爲字符可能..?
非常感謝你。你的回答非常有幫助。雖然,我更接近目標,但問題仍未解決。對於小型html文件,該解決方案可以很好地工作,但是,對於大型文件,它並沒有給出正確的位置。獲得的位置總是由幾個字符到幾十個字符錯位。有什麼想法爲什麼?再次感謝。附:我使用您建議的代碼 – Davita
@Davita更新了我的問題,請檢查我發佈的更新。 – Noseratio
非常感謝:) – Davita