如何在用户书写时在 RichTextBox 中用不同的颜色为不同的单词着色,并在单击该彩色文本时引发事件

How to color different words with different colors in a RichTextBox while a user is writing and raise an event when that colored text is clicked

当用户在富文本框中写一些词时,如果该词与某个特定词匹配,那么该词的颜色应该会自动改变。

当用户点击那个特定的彩色文本时,它应该引发一个事件。

首先将事件添加到您的富文本框文本已更改,然后 如果这是一个特定的单词,您需要更改文本的颜色,例如:Munis , Ali

   private void Rchtxt_TextChanged(object sender, EventArgs e)
            {
                this.CheckKeyword("Munis", Color.Purple, 0);
                this.CheckKeyword("Ali", Color.Green, 0);
            }

鉴于要求:

1) A User inserts some text in a RichTextBox Control.
2) If the word entered is part of a pre-defined list of words, that word should change color (so, define a relation between a word and a color).
3) When a mouse Click event is generated on a colored word, an event is raised, to notify which word was clicked.

可能的结果(复制视觉示例中的内容):

使用自定义 EventArgs 定义自定义 EventHandler:

public class WordsEventArgs : EventArgs
{
    private string m_word;
    public WordsEventArgs(string word) { m_word = word; }
    public string Word { get { return m_word; } set { m_word = value; } }
}

public delegate void WordsEventHandler(object sender, WordsEventArgs e);
public event WordsEventHandler WordClicked;

protected void OnWordClicked(WordsEventArgs e) => WordClicked?.Invoke(this, e);

订阅活动:

this.WordClicked += new WordsEventHandler(this.Word_Click);

单词列表的简单Class:

public class ColoredWord
{
    public string Word { get; set; }
    public Color WordColor { get; set; }
}

public List<ColoredWord> ColoredWords = new List<ColoredWord>();

用相关颜色的一些单词填充列表,然后将其绑定到 ListBox,调用 FillColoredWords() 方法(换句话说,处理将文本片段与颜色值相关联的对象集合):

public void FillColoredWords()
{
    ColoredWords.Add(new ColoredWord { Word = "SIMPLE", WordColor = Color.Goldenrod });
    ColoredWords.Add(new ColoredWord { Word = "COLORED", WordColor = Color.Salmon });
    ColoredWords.Add(new ColoredWord { Word = "TEXT", WordColor = Color.DarkCyan });
    this.listBox1.DisplayMember = "Word";
    this.listBox1.DataSource = ColoredWords;
}

KeyPress 事件中,评估最后输入的单词是否是要着色的单词列表的一部分:

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    int currentPosition = richTextBox1.SelectionStart;

    if (e.KeyChar == (char)Keys.Space && currentPosition > 0 && richTextBox1.Text.Length > 1) {
        int lastSpacePos = richTextBox1.Text.LastIndexOf((char)Keys.Space, currentPosition - 1);
        lastSpacePos = lastSpacePos > -1 ? lastSpacePos + 1 : 0;

        string lastWord = richTextBox1.Text.Substring(lastSpacePos, currentPosition - (lastSpacePos));
        ColoredWord result = ColoredWords.FirstOrDefault(s => s.Word == lastWord.ToUpper());

        richTextBox1.Select(lastSpacePos, currentPosition - lastSpacePos);
        if (result != null) {
            if (richTextBox1.SelectionColor != result.WordColor) { 
                richTextBox1.SelectionColor = result.WordColor;
            }
        }
        else {
            if (richTextBox1.SelectionColor != richTextBox1.ForeColor) { 
                richTextBox1.SelectionColor = richTextBox1.ForeColor;
            }
        }
        richTextBox1.SelectionStart = currentPosition;
        richTextBox1.SelectionLength = 0;
        richTextBox1.SelectionColor = richTextBox1.ForeColor;
    }
}

MouseClick事件中,验证事件是否在彩色词上产生。
在这种情况下,引发自定义 OnWordClicked() 事件:

private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
{
    if (richTextBox1.SelectionColor.ToArgb() != richTextBox1.ForeColor.ToArgb()) {
        try {
            int wordInit = richTextBox1.Text.LastIndexOf((char)32, richTextBox1.SelectionStart);
            wordInit = wordInit > -1 ? wordInit : 0;
            int wordEnd = richTextBox1.Text.IndexOf((char)32, richTextBox1.SelectionStart);
            string wordClicked = richTextBox1.Text.Substring(wordInit, wordEnd - wordInit) + Environment.NewLine;
            OnWordClicked(new WordsEventArgs(wordClicked));
        }
        catch (Exception) {
            //Handle a fast DoubleClick: RTB is a bit dumb.
            //Handle a word auto-selection that changes the `.SelectionStart` value
        }
    }
}

在自定义事件中,您可以将点击的单词附加到文本框(或做任何您想用它做的其他事情):

private void Word_Click(object sender, WordsEventArgs e)
{
    textBox1.AppendText(e.Word);
}