我正在尝试使用语法高亮显示一个TextBox(用于VB.NET 2008中的(HTML / CSS)。
我认为如果我使用RichTextBox.Find(),我可以为特定文本着色,但是我需要调用RichTextBox.DeselectAll()。
问题是光标跳转到RTB的开头。
我正在使用WinForms 有什么想法吗?
答案 0 :(得分:3)
您可以使用SelectionStart
属性来获取和设置光标位置。
因此,你可以写,
Dim selStart As Integer = rtb.SelectionStart
'Do things
rtb.SelectionStart = selStart
答案 1 :(得分:-1)
Imports System.Text.RegularExpressions
Public Class Form1
'Create a Html Keyword Regex
Dim htmlkeywords As New System.Text.RegularExpressions.Regex("<html>|</html>|<head>|</head>|<meta|<p>|</p>|<div>|</div>") <----add as many terms as you like between the () don't forget the pipe symbol between each term in the Regex.
'Then in your Richtextbox textchanged event add this
Private Sub rtText_TextChanged(sender As Object, e As EventArgs) Handles rtText.TextChanged
Dim selStart As Integer = rtText.SelectionStart
Do Until False
For Each keyWordMatch As Match In htmlkeywords.Matches(rtText.Text)
rtText.Select(keyWordMatch.Index, keyWordMatch.Length)
rtText.SelectionColor = Color.Purple
rtText.SelectionStart = rtText.Text.Length 'this puts the caret at the end
rtText.SelectionLength = 0 ' of the word
Next keyWordMatch
Exit Do
Loop
rtText.SelectionColor = Color.Black
rtText.SelectionStart = selStart ' this makes sure that if your caret is behind a word and you press enter to move a text down a line; the caret will stay in position on the next line that you start typing on. You can remove this code to see what I'm talking about
End Sub
rtText
是我的RichTextBox名称。这会将您想要的单词更改为任何颜色,然后将其更改为黑色,您可以更改哪些颜色。希望这有帮助!