Home > Backend Development > C++ > How Can I Colorize Different Segments of Text within a RichTextBox?

How Can I Colorize Different Segments of Text within a RichTextBox?

Patricia Arquette
Release: 2025-01-25 17:08:10
Original
675 people have browsed it

How Can I Colorize Different Segments of Text within a RichTextBox?

In the Richtextbox, the text fragment is colorful

The text display in the RichTextBox control usually needs to use different colors to highlight the specific part. Consider such a scenario: You have a dynamic string, which contains different content. In this case, you may want to allocate different colors for the timestamp, username and message itself.

In order to achieve this coloring, a expansion method can be achieved to re -load the APPENDTEXT method of Richtextbox and add a color parameter:

Using this expansion method, you can color the various parts of the string shown below:
<code class="language-C#">public static class RichTextBoxExtensions
{
    public static void AppendText(this RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;
        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor; //重置颜色
    }
}</code>
Copy after login

This technology provides precise control of the color coloring of Richtextbox content, which enhances its visual attractiveness and readability.
<code class="language-C#">string userid = "USER0001";
string message = "访问被拒绝";
RichTextBox box = new RichTextBox
{
    Dock = DockStyle.Fill,
    Font = new Font("Courier New", 10)
};

box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);

Form form = new Form { Controls = { box } };
form.ShowDialog();</code>
Copy after login

The above is the detailed content of How Can I Colorize Different Segments of Text within a RichTextBox?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template