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

后端 未结 3 527
南方客
南方客 2021-01-28 16:52
private void LoadKeys(Dictionary> dictionary, string FileName)
        {
           string line = System.String.Empty;
           using (         


        
相关标签:
3条回答
  • 2021-01-28 17:04

    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." i.e. 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.

    0 讨论(0)
  • 2021-01-28 17:05
    public void ColorText(RichTextBox box, Color color)
            {
                box.Select(start, 5);
                box.SelectionColor = color;
            } 
    
    0 讨论(0)
  • 2021-01-28 17:15

    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;
    
    0 讨论(0)
提交回复
热议问题