Jeg har lavet et lille eksempel for at give dig en idé om, hvordan det kan gøres. Denne farver kun den første instans af ordet "Google" richEdit'en rød, så hvis du vil farve alle forekomster røde skal du nok bruge regulære udtryk; derfor har jeg puttet en using System.Text.RegularExpressions; op for oven.
- using System;
- using System.Text.RegularExpressions;
- using System.Windows.Forms;
- using System.Drawing;
-
- class Program : Form
- {
- [STAThread]
- static void Main(string[] args)
- {
- Application.EnableVisualStyles();
- Application.Run(new Program());
- }
-
- RichTextBox richEdit;
-
- public Program()
- {
- richEdit = new RichTextBox();
- richEdit.Multiline = false;
- richEdit.HideSelection = true;
- richEdit.Location = new Point(10, 10);
- richEdit.Size = new Size(ClientSize.Width - richEdit.Location.X * 2, 22);
- richEdit.TextChanged += new EventHandler(richEdit_TextChanged);
-
- Controls.Add(richEdit);
- richEdit.Focus();
- }
-
- string word = "Google";
- int caretPos;
- Color selColor = Color.Black;
-
- void richEdit_TextChanged(object sender, EventArgs e)
- {
- if (richEdit.Text.IndexOf(word) < 0)
- return;
-
- selColor = richEdit.SelectionColor;
- caretPos = richEdit.SelectionStart;
- this.Focus();
-
- richEdit.Select(richEdit.Text.IndexOf(word), word.Length);
- richEdit.SelectionColor = Color.Red;
- richEdit.SelectionLength = 0;
- richEdit.SelectionStart = caretPos;
- richEdit.SelectionColor = selColor;
-
- richEdit.Focus();
- }
- }