只读richtextbox更改关键字C#的颜色 [英] Readonly richtextbox changing color of keyword C#

查看:204
本文介绍了只读richtextbox更改关键字C#的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个丰富的文本框,用于显示Hello World程序的示例,并希望诸如使用,命名空间,类,静态,无效,字符串之类的关键字显示为蓝色。

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.

我有正在使用显示为蓝色,但是只有当用户开始键入或键入正在使用
时,我才希望仅将richtextbox只读允许用户输入

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

这是我的代码:

    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;
            };
        }
    }

我很难弄清楚该怎么做只读rtb。
我如何编辑代码以在只读rtb中初始化时显示蓝色文本

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

感谢您的帮助

推荐答案

无需订阅 TextChanged 事件。

将代码放在单独的方法中:

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;
        };
    }
}

RichTextBox

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

ApplySyntaxHighlite();

这篇关于只读richtextbox更改关键字C#的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆