簡體   English   中英

在RichTextBox中更改顏色的問題

[英]Issues changing color in richtextbox

我正在嘗試遍歷Richtextbox中的一些預鍵入文本,並根據其前綴將特定單詞/行的顏色更改為一種顏色,到目前為止,不同的前綴是[b],[f]和[e] 。 在此示例中,我僅使用[b]。 我已經嘗試過使用while / foreach循環,但是它們似乎並未遍歷整個文本。 以下是我最近使它起作用的方法,但它僅適用於文本的第一行。 有人可以向我指出正確的方向嗎?

 private void AboutBox_Load(object sender, EventArgs e)
    {
        textBox1.Select(0, 0);
        using (StringReader reader = new StringReader(richTextBox1.Text))
        {
            string line = string.Empty;
            do
            {
                line = reader.ReadLine();

                if ((line != null && line.Contains("[b]")))
                  {
                      richTextBox1.Select(richTextBox1.Text.IndexOf("[b]"), "[b]".Length);
                      richTextBox1.SelectionColor = Color.Green;
                  }
            } while (line != null);
        }
    }

無需將文本復制到字符串,您可以通過RichTextBox的Find()方法直接使用它:

    void AboutBox_Load(object sender, EventArgs e)
    {
        this.ColorPrefix(richTextBox1, "[b]", Color.Green);
        this.ColorPrefix(richTextBox1, "[f]", Color.Red); // change the color!
        this.ColorPrefix(richTextBox1, "[e]", Color.Yellow); // change the color!
    }

    private void ColorPrefix(RichTextBox rtb, string prefix, Color color)
    {
        int position = 0, index = 0;
        while ((index = rtb.Find(prefix, position, RichTextBoxFinds.None)) >= 0)
        {
            rtb.Select(index, prefix.Length);
            rtb.SelectionColor = color;
            position = index + 1;
        }
        rtb.Select(rtb.TextLength, 0);
    }

該行將始終選擇相同的項目:

richTextBox1.Select(richTextBox1.Text.IndexOf("[b]"), "[b]".Length);

所以我建議這樣的事情:

    private void AboutBox_Load(object sender, EventArgs e)
    {
        string text = richTextBox1.Text;
        int position = 0, index = 0;
        while ((index = text.IndexOf("[b]", position)) >= 0)
        {
            richTextBox1.Select(index, 3);
            richTextBox1.SelectionColor = Color.Green;
            position = index + 1;
        }
    }

如果您想突出顯示語法,建議您使用FastColoredTextBox控件:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM