2014-02-20 48 views
-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將某種標籤解釋爲字符可能..?

回答

3

甲啞方法(使用JavaScript符號爲簡單起見):

  1. 創建文本範圍document.body
    var bodyRange = document.body.createTextRange(); bodyRange.moveToElementText(document.body);
    現在bodyRange.text對應於全文。
  2. 使用bodyRange.moveStart("character", 1)可以一次向前移動一個字符,並將其起始位置與您選擇的範圍進行比較,起始位置爲bodyRange.compareEndPoints("StartToStart", range。當他們匹配時,您已經在全文中找到了開頭的位置。
  3. bodyRange.collapse(true),這會將範圍的末端移動到範圍的開始處。
  4. 使用bodyRange.moveEnd("character", 1)一次向前移動一個字符,並將其開始與您選擇的範圍(從bodyRange.compareEndPoints("EndToEnd", range開始)進行比較。當它們匹配時,您已經在全文中找到了末尾的位置。

您可以提高該算法通過一次一次移動一個詞或一個句子moveStart/moveEnd,由一個字符,然後精細匹配。

此外,還有一個更好的方法,它使用standard DOM Range and Selection API。我描述了它here

更新,請嘗試以下更新到您的代碼(未經測試):

var tempRange = bodyRange.duplicate(); 
while (bodyRange.compareEndPoints("StartToStart", range) != 0) 
{ 
    bodyRange.moveStart("character", 1); 
    tempRange.setEndPoint("EndToStart", bodyRange); 
    //tempRange.EndToStart(bodyRange); 
    if (String.Compare(tempRange.text, ((String)bodyText).Substring(counter)) != 0) 
     ++counter; 
} 
MessageBox.Show(str.Substring(counter, 20)); 
+0

非常感謝你。你的回答非常有幫助。雖然,我更接近目標,但問題仍未解決。對於小型html文件,該解決方案可以很好地工作,但是,對於大型文件,它並沒有給出正確的位置。獲得的位置總是由幾個字符到幾十個字符錯位。有什麼想法爲什麼?再次感謝。附:我使用您建議的代碼 – Davita

+0

@Davita更新了我的問題,請檢查我發佈的更新。 – Noseratio

+1

非常感謝:) – Davita

相關問題