简体   繁体   中英

How do i color a specific part of text in a richTextBox?

private void LoadKeys(Dictionary<string,List<string>> dictionary, string FileName)
        {
           string line = System.String.Empty;
           using (StreamReader sr = new StreamReader(keywords))
           {
            while ((line = sr.ReadLine()) != null)
            {
                string[] tokens = line.Split(',');
                dictionary.Add(tokens[0], tokens.Skip(1).ToList());
                richTextBox2.AppendText("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]+Environment.NewLine);
                ColorText(richTextBox2, Color.Red);
            }
           } 
        }

And the function ColorText:

public void ColorText(RichTextBox box, Color color)
        {
            box.SelectionStart = box.TextLength; box.SelectionLength = 0;
            box.SelectionColor = color;
            box.SelectionColor = box.ForeColor;
        } 

But it didnt color anything in Red. Nothing changed. I want to be able to color in Red for exmaple only the tokens[0] and in Green tokens[1] for example.

How can i do it ?

public void ColorText(RichTextBox box, Color color)
        {
            box.Select(start, 5);
            box.SelectionColor = color;
        } 

The code you show in ColorText shows you going to the end of the text, setting the selection length to 0, setting the colour to red and then back to forecolor, so not acheiving..

Perhaps you need to do something like

        box.Text = "This is a red color";
        box.SelectionStart = 10;
        box.SelectionLength = 3;
        box.SelectionColor = Color.Red;
        box.SelectionLength = 0;

box.SelectionStart = box.TextLength; - this line of your code can be interpreted as "start highlighting the text starting at the end of box's text." ie Select no text because there can't be any text after the last of the text.

box.SelectionLength = 0; - Further still, this line can be interpreted as "highlight 0 amount of text." You've double made sure you're selecting no text haha.

I'm not sure how you want to determine what text to select, but I'd use something like:

        public void ColorSelectedText(RichTextBox textBox, Int32 startPos, Int32 length, Color color)
        {
            textBox.Select(startPos, length);
            textBox.SelectionColor = color;
        } 

Pass in your textbox object and your colour.

The integers you pass can be thought of as if you were highlighting the text with your mouse cursor:

startPos is where you'd click your mouse down, and 'length' would be the amount of characters between startPos and where you release your mouse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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