开发者

"Caret Position" in VB.NET for syntax highlighting

开发者 https://www.devze.com 2022-12-14 01:23 出处:网络
I\'m trying to make a TextBox with syntax h开发者_开发问答ighlighting (for (HTML/CSS) in VB.NET 2008.

I'm trying to make a TextBox with syntax h开发者_开发问答ighlighting (for (HTML/CSS) in VB.NET 2008.

I figured that if I use RichTextBox.Find(), I can color specific text, but then I need to call RichTextBox.DeselectAll().

The problem is that the the cursor jumps to the beginning of the RTB.

I'm using WinForms.

Any ideas?


You can get and set the cursor position using the SelectionStart property.

Therefore, you can write,

Dim selStart As Integer = rtb.SelectionStart
'Do things
rtb.SelectionStart = selStart


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 is my RichTextBox name. This will change the word you want to whatever color then change it back to black, which you can change which colors do what. Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消