如何在富文本框中突出显示单词的所有出现? [英] How do I highlight all ocurrences of a word in a richtextbox?

查看:87
本文介绍了如何在富文本框中突出显示单词的所有出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示RichTextBox中一个单词的所有出现;我试图找到每个单词出现的位置,并且效果很好,但是当我尝试突出显示某个单词时,它只会突出显示一个单词,或者会突出显示另一件事.这是代码:

Hi i was trying to highlight all occurrences of a word in a richtextbox; I tried to find the positions of every occurrence of a word and it works fine, but when i tried to highlight it just highlights one or it highlights another things. Here is the code:

Public sub buscar (Byval cadena as String)

        Dim linea As String
        Dim numlineas As Integer
        Dim posicion As Integer = 0
        Dim posicion2 As Integer = 0
        Dim myRegex As New Regex("\w+")
        Dim palabras As MatchCollection
        Dim contador As Integer
        Dim cont As Integer

        numlineas = RichTextBox1.Lines.Count() - 1
        posicion = RichTextBox1.Find(cadena)

        For contador = 0 To numlineas Step 1

            linea = RichTextBox1.Lines(contador)
            cont = 0
            palabras = myRegex.Matches(linea)

            
            For Each ele As Match In palabras
                If ele.ToString() = cadena Then
                    
                    ' posicion Gets the position of the element
                    posicion = ele.Index()

                    'MsgBox(posicion.ToString()) 
                    
                    'highlight the word
                    RichTextBox1.SelectionStart = posicion
                    RichTextBox1.SelectionLength = cadena.Length()
                    RichTextBox1.SelectionColor = Color.Red

                End If
            Next
           

        Next
End Sub

推荐答案

在Anhinav的帮助下设法解决问题是一件好事;本文中的解决方案看起来是正确的.

为了以防万一,我想把这个想法说清楚:您不应真正地突出显示"任何内容,如果突出显示是指设置可以在剪贴板操作中使用的选择.想法是记住一定范围的文本范围,并修改渲染选择的渲染属性,例如背景色.您应该记住控件成员中的数据,以清除选择的呈现并执行在此范围范围内可能需要的任何操作(包括剪贴板操作,间接).

抱歉,如果这个答案是多余的,但这个想法是可行的.

—SA
It''s good that you managed to make a solution with the help of Anhinav; the solution in the article looks correct.

Just in case, I wanted to make the idea clear: you should not really "highlight" anything, if by highlighting you mean setting the selection which can be used in a clipboard operation. The idea is to remember the certain set of text ranges and modify the rendering attributes for such selection, like background color. You should remember this data in a controls member to clean this rendering of selection and to perform any operations you may need over this set of ranges (including clipboard operations, indirectly).

Sorry if this answer is redundant, but the idea is a working one.

—SA


本文 [ ^ ]适用于C#,但应该可以帮助您.
This article[^] is for C# but should help you out.


这篇关于如何在富文本框中突出显示单词的所有出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆