Home > Backend Development > C++ > How Can I Color Different Parts of Text Appended to a RichTextBox in C#?

How Can I Color Different Parts of Text Appended to a RichTextBox in C#?

DDD
Release: 2025-01-25 17:01:11
Original
959 people have browsed it

How Can I Color Different Parts of Text Appended to a RichTextBox in C#?

Colorize different parts of RichTextBox append text in C#

Question:

You want to selectively color certain parts of the string attached to the RichTextBox. Specifically, you want the bracketed text, the user information, and the actual message to be drawn in different colors.

Solution: Extension method with color parameter

To achieve your goals, you can use an extension method to overload the AppendText method and introduce a color parameter. Here is the code:

<code class="language-csharp">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

Usage:

After defining the extension method, it is very simple to use. Just use it as shown in the following code:

<code class="language-csharp">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

Note:

Please note that excessive text output may cause the RichTextBox to flicker. Please refer to the C# Corner article mentioned in the answer for possible solutions.

The above is the detailed content of How Can I Color Different Parts of Text Appended to a RichTextBox in C#?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template