Sipo Sipo - 9 months ago 52
C# Question

How to create a label with multiple styles in it using C# winforms?

When you create a

in WinForms, the
and the
, which produce this kind of

Normal label

I want to be able to set a different
, different
and different
(bold) to some of the words inside a label. Something like this:

A label with different ForeColors and BackColors in it.

I googled it but all I have found is answers about changing the entire label style. So how can I accomplish what I described?

If there isn't a simple way to do it using built-in C# stuff, how to approach this?

Answer Source

I'd agree with ChrisF that a readonly RichTextBox is best suited for this purpose.
Here's an example of a readonly RichTextBox control that I've used in the past.

public class DisabledRichTextBox : RichTextBox
    private const int WmSetfocus = 0x07;
    private const int WmEnable = 0x0A;
    private const int WmSetcursor = 0x20;

    protected override void WndProc(ref Message m)
        if (!(m.Msg == WmSetfocus || m.Msg == WmEnable || m.Msg == WmSetcursor))
            base.WndProc(ref m);

To use the code:

  1. Add a new class to your project. Personally I'd add a new .cs file called something like DisabledRichTextBox.cs. Paste this code in between the namespace tag:

    using whatever;
    namespace YourNamespace 
        // Code here 
  2. Build your project as normal.

  3. You should now have a new control in your toolbox on the left named DisabledRichTextBox or whatever you called it.

enter image description here

  1. Add this to your project in the same way you would any other control.
  2. Set the .Rtf (richtext) property of this new RichTextBox to some appropriate RichText.