i am trying to make my WebBrowser control highlight some words. i found t开发者_运维问答his example but i don't get how to translate that to c#. any help would be appreciated :)
The code is already in C#. You need to add a reference to get the interface type definitions. They are COM types, imported from an Internet Explorer type library.
Project + Add Reference, Browse tab, select c:\windows\system32\mshtml.tlb. Put using mshtml;
at the top of your source code file. The code is pretty sloppy with the COM types, if you use VS2010 then you'll have to select the added reference (MSHTML) in the References node and set the Embed Interop Types property to False and the Copy Local property to True. Deploy the Microsoft.mshtml.dll interop library you'll find the build directory along with your program.
The example mentioned will actually replace the content. So it might get wrong output when finding text matches with the text with Capital letters. So might be useful to use indexOf and Insert rather than Replace.
Here is How.
Private Sub WebBrowser_DocumentCompleted(sender As Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser.DocumentCompleted
Dim doc2 As mshtml.IHTMLDocument2 = WebBrowser.Document.DomDocument
Dim ReplacementTag As String = "<span style='background-color: rgb(255, 255, 0);'>"
Dim strBuilder As StringBuilder = New StringBuilder(doc2.body.outerHTML)
Dim HTMLString As String = strBuilder.ToString()
If Me.m_NoteType = ExtractionNoteType.SearchResult Then
Dim SearchWords As New List(Of String)
SearchWords.AddRange(Me.txtNoteSearch.Text.Trim.Split(" "))
For Each item As String In SearchWords
Dim index As Integer = HTMLString.IndexOf(item, 0, StringComparison.InvariantCultureIgnoreCase)
''If index > 0 Then
While (index > 0 AndAlso index < HTMLString.Length)
HTMLString = HTMLString.Insert(index, ReplacementTag)
HTMLString = HTMLString.Insert(index + item.Length + ReplacementTag.Length, "</span>")
index = HTMLString.IndexOf(item, index + item.Length + ReplacementTag.Length + 7, StringComparison.InvariantCultureIgnoreCase)
End While
''End If
''strBuilder.Replace(item, "<span style='background-color: rgb(255, 255, 0);'>" + item + "</span>")
Next
Else
''strBuilder.Replace("<span style='background-color: rgb(255, 255, 0);'>", "<span style='background-color: rgb(255, 255, 255);'>")
End If
doc2.body.innerHTML = HTMLString
End Sub
精彩评论