【问题标题】:Readonly richtextbox changing color of keyword C#只读richtextbox更改关键字C#的颜色
【发布时间】:2015-06-06 09:53:15
【问题描述】:

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

我已经让“使用”显示为蓝色,但仅当用户开始键入或键入“使用”时 我希望richtextbox 只读,不允许用户输入

这是我的代码:

    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 中初始化时显示蓝色文本

感谢您的帮助

【问题讨论】:

    标签: c# winforms colors richtextbox


    【解决方案1】:

    无需订阅TextChanged 事件。

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

    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();
    

    【讨论】:

    • 谢谢!我将如何修改查找字符串以包含“命名空间”和“类”等
    • 当我删除突出显示的关键字的字符时,字体样式仍然存在,有没有办法解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 2012-07-28
    • 2017-11-20
    • 2010-11-06
    • 2016-09-01
    相关资源
    最近更新 更多