【问题标题】:"Caret Position" in VB.NET for syntax highlightingVB.NET 中用于语法高亮的“插入符号位置”
【发布时间】:2010-12-27 12:12:56
【问题描述】:
我正在尝试在 VB.NET 2008 中制作一个带有语法高亮的文本框(用于(HTML/CSS)。
我想如果我使用 RichTextBox.Find(),我可以为特定文本着色,但是我需要调用 RichTextBox.DeselectAll()。
问题是光标跳到了RTB的开头。
我正在使用 WinForms。
有什么想法吗?
【问题讨论】:
标签:
vb.net
winforms
richtextbox
syntax-highlighting
【解决方案1】:
您可以使用SelectionStart 属性获取和设置光标位置。
因此,你可以写,
Dim selStart As Integer = rtb.SelectionStart
'Do things
rtb.SelectionStart = selStart
【解决方案2】:
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 名称。这会将您想要的单词更改为任何颜色,然后将其更改回黑色,您可以更改哪些颜色可以做什么。希望这会有所帮助!