Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim adapter As New Rtf.RichTextBoxAdapter(RichTextBox1) adapter.ColorTexts.Add("abc", Color.Blue) adapter.ColorTexts.Add("efg", Color.Red) adapter.ColorTexts.Add("\.Train", Color.Green) End Sub End Class Namespace Rtf 'RTFの仕様 'http://msdn.microsoft.com/en-us/library/aa140301(v=office.10).aspx#rtfspec_12 'RTFの例 '{\rtf1\ansi\ansicpg932\deff0\deflang1033\deflangfe1041{\fonttbl{\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fcharset128 MS UI Gothic;}} '{\colortbl ;\red0\green0\blue255;\red255\green0\blue0;} '\viewkind4\uc1\pard\lang1041\f0\fs18 AAAAA\par '\cf1 abc\cf0\par 'BBBBB\par '\cf2 efg\cf0\par 'CCCCC\f1\par '} Public Class RichTextBoxAdapter Public WithEvents Source As RichTextBox Public ColorTexts As New Dictionary(Of String, Color) Public Sub New(ByVal source As RichTextBox) Me.Source = source End Sub Private Sub source_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Source.TextChanged If ColorTexts.Count = 0 Then Return End If 'TextBox1.Text = RichTextBox1.Rtf Static stopper As Boolean If stopper Then Return End If stopper = True Dim typedSender As RichTextBox = sender Dim currentPos As Integer = typedSender.SelectionStart Dim rtf As New Rtf.Document(typedSender.Rtf) rtf.ClearTextMark() For Each Text As String In ColorTexts.Keys Dim color As Color = ColorTexts(Text) rtf.MarkText(Text, color) Next typedSender.Rtf = rtf typedSender.SelectionStart = currentPos stopper = False End Sub End Class Public Class Document Public Rtf As String Public ColorTable As ColorTable Public Sub New(ByVal rtf As String) Me.Rtf = rtf Me.ColorTable = New ColorTable(rtf) End Sub 'テキストの色をすべてクリアする。 Public Sub ClearTextMark() Dim pattern As String = "\\cf[1-9]+?\s+?" Me.Rtf = System.Text.RegularExpressions.Regex.Replace(Me.Rtf, pattern, "") pattern = "\\cf0" Me.Rtf = System.Text.RegularExpressions.Regex.Replace(Me.Rtf, pattern, "") End Sub ''' <summary> ''' Textは正規表現のエスケープ付きで指定してください。 ''' たとえば、「Dim」が対象の時は単に"Dim"で良いですが、 ''' .Trainが対象の時は"\.Train"とする必要があります。 ''' </summary> ''' <param name="text"></param> ''' <param name="color"></param> ''' <remarks></remarks> Public Sub MarkText(ByVal text As String, ByVal color As Color) 'colorが現在のColorTableにあるか確認 Dim colorIndex As Integer = Me.ColorTable.IndexOf(color) + 1 If colorIndex < 1 Then '存在しなければ追加する Me.ColorTable.Add(color) colorIndex = Me.ColorTable.IndexOf(color) + 1 End If '色がついたテキストは次のようになっている。 'ここでcf1の1がColorIndex '\cf1 abc\par Dim result As String = "\cf" & colorIndex & " " & text & "\cf0" Me.Rtf = System.Text.RegularExpressions.Regex.Replace(Me.Rtf, text, result) End Sub