开发者

How to apply colour formatting to a Richtextbox *as the user types* (VB.Net)

I have a RichTextBox with an OnChanged event. The OnChanged event should look at each line in the RichTextBox and if the line is of prime length colour it red, otherwise colour it black. How do I do this? I think it is possible to select from index a to index b and set selection colour, but I think this will lose my cursor position. How do I also preserve cursor position? Thanks for any sugg开发者_如何学编程estions.


Look at SelectionStart and SelectionLength to select the text to highlight.

To keep the cursor position I think you can just store the current SelectionStart before you start highlighting and then reset it to that value after you've finished the highlighting.

Just be careful though if the user keeps typing while you're off highlighting. You'd probably have to intercept the keyboard events and cache them and then insert them after you've reset the SelectionStart to the correct location (or it might be easier, though less user friendly, to just ignore any keypresses while you're doing the highlighting).


Private Sub txtKeys_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtKeys.TextChanged
    Dim iStart As Int32 = txtKeys.SelectionStart
    Dim iPos As Int32 = 0
    For Each s As String In Split(txtKeys.Text, vbLf)
        If s.Length > 0 Then
            txtKeys.Select(iPos, iPos + s.Length)
            If isPrime(s.Length) Then
                txtKeys.SelectionColor = Color.GreenYellow
            Else
                txtKeys.SelectionColor = Color.Black
            End If
        End If
        iPos += s.Length + 1
    Next
    txtKeys.Select(iStart, 0)
End Sub

Sorry about the lack of comments! I imagine this will get massively inefficient when applied to a large .text property but this is not the intended use of the textbox.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜