vb.net - Multicolor RichTextBox

后端 未结 1 1697
醉酒成梦
醉酒成梦 2020-12-18 08:34

I would like to make a line of text in my richtextbox multicolor. I have tried various implementations provided on the web and read up on SelectedText and other topics but c

相关标签:
1条回答
  • 2020-12-18 09:03

    It's not really clear what you're trying to achieve. I'm not sure I understand the bracketed formatting nearly as well as I would an image that you mocked up in Paint. But here goes anyway...

    I suspect there are a couple of problems with your existing code. First up is the location of the cursor when you insert new text. What's supposed to come after the first snippet actually gets inserted before it because of where the insertion mark is located. To fix that, you need to move it manually.

    You're also assigning a string of text to the Text property at the end of your code, which does not preserve the existing formatting information. I suspect that the simplest thing for you to do is to use the AppendText method, instead.

    And finally, I recommend using the simpler overload to create a new font, since the only thing you want to change is the style. The advantage of using this instead is that you don't have to hardcode the name and size of the font in your code, in case you want to change it later.

    Try rewriting your code to this instead:

    ' Insert first snippet of text, with default formatting
    RichTextBox1.Text = "This is black "
    
    ' Move the insertion point to the end of the line
    RichTextBox1.Select(RichTextBox1.TextLength, 0)
    
    'Set the formatting and insert the second snippet of text
    RichTextBox1.SelectionFont = New Font(RichTextBox1.Font, FontStyle.Bold)
    RichTextBox1.SelectionColor = Color.Green
    RichTextBox1.AppendText("[BOLD GREEN]")
    
    ' Revert the formatting back to the defaults, and add the third snippet of text
    RichTextBox1.SelectionFont = RichTextBox1.Font
    RichTextBox1.SelectionColor = RichTextBox1.ForeColor
    RichTextBox1.AppendText(" black again")
    

    The result will look like this:

       sample RichTextBox with formatted text

    0 讨论(0)
提交回复
热议问题