رنگی کردن کلمات خاص در RichTextBox
اگر بخواهید هنگام نوشتن و یا کپی برخی کلمات خاص در richtextbox رنگ آنها تغییر کند می توانید از کد زیر استفاده نمایید :
using System; using System.Drawing; using System.Windows.Forms; namespace MultiColorRichTextBox { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void CheckKeyword(string word, Color color, int startIndex) { if (this.richTextBox1.Text.Contains(word)) { int index = -1; int selectStart = this.richTextBox1.SelectionStart; while ((index = this.richTextBox1.Text.IndexOf(word, (index + 1))) != -1) { this.richTextBox1.Select((index + startIndex), word.Length); this.richTextBox1.SelectionColor = color; this.richTextBox1.Select(selectStart, 0); this.richTextBox1.SelectionColor = Color.Black; } } } private void richTextBox1_TextChanged(object sender, EventArgs e) { this.CheckKeyword("while", Color.Red, 0); this.CheckKeyword("if", Color.Blue, 0); } } }
در کد بالا فرض بر این است که ما می خواهیم کلمات if به رنگ آبی و while به رنگ قرمز در آیند :
than