简体   繁体   English

如何根据C#中的字符串更改RichTextBox文本

[英]How to change RichTextBox text depending on a string in C#

So, I am trying to build a RichTextBox which allows me to write code into it and changes the color of the keywords based on C# programming language. 因此,我正在尝试构建一个RichTextBox ,它允许我向其中编写代码并根据C#编程语言更改关键字的颜色。

First of all, I've declared this: 首先,我声明了这一点:

string[] palavraschave = { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", 
     "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto",
     "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", 
     "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", 
     "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", 
     "using", "virtual", "void", "volatile", "while", "add", "alias", "ascending", "descending", "dynamic", "from", "get", "global", "group", 
     "into", "join", "let", "orderby", "partial", "remove", "select", "set", "value", "var", "where", "yield" };

Then I have a method to check the RichTextBox : 然后,我有一种方法来检查RichTextBox

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

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

To call it, I will use this piece of code into the RichTextBox TextChanged event: 要调用它,我将在RichTextBox TextChanged事件中使用以下代码:

this.CheckRichTextBox(palavraschave.ToString(), Color.Blue, 0);

But it does not work. 但这行不通。 What am I doing wrong? 我究竟做错了什么?

You would need to do a for each on the array of words and call your procedure for each word rather calling toString. 您将需要对单词数组中的每个单词执行一个操作,并为每个单词调用过程,而不是调用toString。 Or pass the array to your function and loop in there. 或将数组传递给函数并在其中循环。

But as other people have said there are plenty of solutions for this type of thing already out there. 但是正如其他人所说的那样,已经有很多解决方案。

Consider using something like ColorCode ; 考虑使用诸如ColorCode之类的东西 this work has already been done well, and likely more efficiently. 这项工作已经做得很好,并且可能会更有效。 To do this, add the NuGet package, then replace your RichTextBox with a WebBrowser control, and pass your source text into the colorizer: 为此,添加NuGet包,然后将您的RichTextBox替换为WebBrowser控件,然后将源文本传递到着色器中:

using ColorCode;
[...]
webBrowser1.DocumentText = new CodeColorizer().Colorize(mySourceText, Languages.CSharp);

For info on adding NuGet packages, see here . 有关添加NuGet软件包的信息,请参见此处


Alternatively, if you are looking for a syntax-highlighting text editor, you could use Scintilla. 另外,如果您正在寻找语法高亮的文本编辑器,则可以使用Scintilla。

First add the NuGet package called jacobslusser.ScintillaNET , and this time there's an extra step to make the control appear in the toolbox; 首先添加名为jacobslusser.ScintillaNET的NuGet程序包,这次还有一个额外的步骤使该控件出现在工具箱中。 right-click the Windows Forms toolbox, select 'Choose Items', then 'Browse', and browse to the Scintilla DLL. 右键单击Windows窗体工具箱,选择“选择项目”,然后选择“浏览”,并浏览到Scintilla DLL。 In my project this is here; 在我的项目中,这是这里;

packages\\jacobslusser.ScintillaNET.3.6.3\\lib\\net40\\ScintillaNET.dll

That will add the 'Scintilla' control to the toolbox, and you can drag this to your form. 这会将“ Scintilla”控件添加到工具箱,您可以将其拖动到表单中。 Finally, in the form's Load event, add the following 'recipe' to make it look similar to Visual Studio's syntax highlighting: 最后,在表单的Load事件中,添加以下“食谱”,使其看起来类似于Visual Studio的语法突出显示:

private void Form1_Load(object sender, EventArgs e)
{
    // Configuring the default style with properties
    // we have common to every lexer style saves time.
    scintilla1.StyleResetDefault();
    scintilla1.Styles[Style.Default].Font = "Consolas";
    scintilla1.Styles[Style.Default].Size = 10;
    scintilla1.StyleClearAll();

    // Configure the CPP (C#) lexer styles
    scintilla1.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
    scintilla1.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
    scintilla1.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
    scintilla1.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
    scintilla1.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
    scintilla1.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
    scintilla1.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
    scintilla1.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
    scintilla1.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
    scintilla1.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
    scintilla1.Lexer = Lexer.Cpp;

    // Set the keywords
    scintilla1.SetKeywords(0, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
    scintilla1.SetKeywords(1, "bool byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

}

More about Scintilla here . 有关Scintilla的更多信息,请点击这里 Recipe from here . 这里食谱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM