Readonly richtextbox changing color of keyword C#

好久不见. 提交于 2020-01-25 00:58:09

问题


I have a rich text box that i am using to display an example of the Hello World program and want the keywords such as 'using' 'namespace' 'class' 'static' 'void' 'string' to display blue.

I have got 'using' to display blue but only when the user starts to type or types 'using' I want the richtextbox to be read only not allowing an user input into it

Here is my code:

    private void rtb_TextChanged(object sender, EventArgs e)
    {
        string find = "using";
        if (rtb.Text.Contains(find))
        {
            var matchString = Regex.Escape(find);
            foreach (Match match in Regex.Matches(rtb.Text, matchString))
            {
                rtb.Select(match.Index, find.Length);
                rtb.SelectionColor = Color.Blue;
                rtb.Select(rtb.TextLength, 0);
                rtb.SelectionColor = rtb.ForeColor;
            };
        }
    }

I am having trouble figuring out how to do it for readonly rtb. How could i edit my code to display the blue text on initialize in a readonly rtb

Thanks for your help


回答1:


There's no need to subscribe to the TextChanged event.

Place your code in a separate method:

private void ApplySyntaxHighlite()
{
    string find = "using";
    if (richTextBox1.Text.Contains(find))
    {
        var matchString = Regex.Escape(find);
        foreach (Match match in Regex.Matches(richTextBox1.Text, matchString))
        {
            richTextBox1.Select(match.Index, find.Length);
            richTextBox1.SelectionColor = Color.Blue;
            richTextBox1.Select(richTextBox1.TextLength, 0);
            richTextBox1.SelectionColor = richTextBox1.ForeColor;
        };
    }
}

And call it after you set the text in the RichTextBox:

richTextBox1.Text =
    "using System;\r\nusing System.IO;\r\n\r\nConsole.WriteLine(\"Hello world.\");";

ApplySyntaxHighlite();



来源:https://stackoverflow.com/questions/29396076/readonly-richtextbox-changing-color-of-keyword-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!