gpt4 book ai didi

c# - RichtextBox 中的颜色特定单词

转载 作者:可可西里 更新时间:2023-11-01 08:55:11 31 4
gpt4 key购买 nike

我怎样才能做到,当用户在富文本框中键入“while”或“if”等特定词时,这些词会毫无问题地变成紫色?我试过不同的代码,但没有一个可用。代码如下:

if (richTextBox.Text.Contains("while"))
{
richTextBox.Select(richTextBox.Text.IndexOf("while"), "while".Length);
richTextBox.SelectionColor = Color.Aqua;
}

此外,我希望当用户删除该词或从该词中删除一个字母时,该词的颜色将恢复为默认颜色。我正在制作一个带有代码编辑器的程序。

我正在使用 Visual C#。

谢谢。

最佳答案

将事件添加到您的丰富框文本已更改,

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



private void CheckKeyword(string word, Color color, int startIndex)
{
if (this.Rchtxt.Text.Contains(word))
{
int index = -1;
int selectStart = this.Rchtxt.SelectionStart;

while ((index = this.Rchtxt.Text.IndexOf(word, (index + 1))) != -1)
{
this.Rchtxt.Select((index + startIndex), word.Length);
this.Rchtxt.SelectionColor = color;
this.Rchtxt.Select(selectStart, 0);
this.Rchtxt.SelectionColor = Color.Black;
}
}
}

关于c# - RichtextBox 中的颜色特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21980554/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com