Pergunta

É possível formatar determinado texto em um rótulo WinForm em vez de dividir o texto em vários rótulos?Desconsidere as tags HTML no texto da etiqueta;é usado apenas para mostrar meu ponto de vista.

Por exemplo:

Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text.  This is <i>italicized</i> text."

O que produziria o texto no rótulo como:

Isso é audacioso texto.Isso é itálico texto.

Foi útil?

Solução

Isso não é possível com um rótulo WinForms como está.A etiqueta deve ter exatamente uma fonte, com exatamente um tamanho e uma face.Você tem algumas opções:

  1. Use rótulos separados
  2. Crie uma nova classe derivada de Control que faça seu próprio desenho via GDI+ e use-a em vez de Label;esta é provavelmente a sua melhor opção, pois lhe dá controle total sobre como instruir o controle para formatar seu texto
  3. Use um controle de rótulo de terceiros que permitirá inserir trechos de HTML (há vários - verifique CodeProject);esta seria a implementação do nº 2 por outra pessoa.

Outras dicas

Na verdade não, mas você pode fingir com um RichTextBox somente leitura sem bordas.RichTextBox oferece suporte ao formato Rich Text (rtf).

Outra solução alternativa, atrasada para a festa:se você não quiser usar um controle de terceiros e quiser apenas chamar a atenção para parte do texto em seu rótulo, e você está bem com sublinhados, você pode usar um LinkLabel.

Observe que muitos consideram isso um 'crime de usabilidade', mas se você não está projetando algo para consumo do usuário final, então pode ser algo que você está preparado para ter em sua consciência.

O truque é adicionar links desativados às partes do texto que você deseja sublinhar e, em seguida, definir globalmente as cores dos links para corresponder ao restante do rótulo.Você pode definir quase todas as propriedades necessárias em tempo de design, exceto Links.Add() pedaço, mas aqui estão eles em código:

linkLabel1.Text = "You are accessing a government system, and all activity " +
                  "will be logged.  If you do not wish to continue, log out now.";
linkLabel1.AutoSize = false;
linkLabel1.Size = new Size(365, 50);
linkLabel1.TextAlign = ContentAlignment.MiddleCenter;
linkLabel1.Links.Clear();
linkLabel1.Links.Add(20, 17).Enabled = false;   // "government system"
linkLabel1.Links.Add(105, 11).Enabled = false;  // "log out now"
linkLabel1.LinkColor = linkLabel1.ForeColor;
linkLabel1.DisabledLinkColor = linkLabel1.ForeColor;

Resultado:

enter image description here

Solução funcionou para mim - usando RichEditBox personalizado.Com as propriedades corretas, parecerá um rótulo simples com suporte em negrito.

1) Primeiro, adicione sua classe RichTextLabel personalizada com o cursor desativado:

public class RichTextLabel : RichTextBox
{
    public RichTextLabel()
    {
        base.ReadOnly = true;
        base.BorderStyle = BorderStyle.None;
        base.TabStop = false;
        base.SetStyle(ControlStyles.Selectable, false);
        base.SetStyle(ControlStyles.UserMouse, true);
        base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);

        base.MouseEnter += delegate(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
        };
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x204) return; // WM_RBUTTONDOWN
        if (m.Msg == 0x205) return; // WM_RBUTTONUP
        base.WndProc(ref m);
    }
}

2) Divida sua frase em palavras com o sinalizador IsSelected, que determina se a palavra deve estar em negrito ou não:

        private void AutocompleteItemControl_Load(object sender, EventArgs e)
    {
        RichTextLabel rtl = new RichTextLabel();
        rtl.Font = new Font("MS Reference Sans Serif", 15.57F);
        StringBuilder sb = new StringBuilder();
        sb.Append(@"{\rtf1\ansi ");
        foreach (var wordPart in wordParts)
        {
            if (wordPart.IsSelected)
            {
                sb.Append(@"\b ");
            }
            sb.Append(ConvertString2RTF(wordPart.WordPart));
            if (wordPart.IsSelected)
            {
                sb.Append(@"\b0 ");
            }
        }
        sb.Append(@"}");

        rtl.Rtf = sb.ToString();
        rtl.Width = this.Width;
        this.Controls.Add(rtl);
    }

3) Adicione função para converter seu texto em rtf válido (com suporte unicode!):

   private string ConvertString2RTF(string input)
    {
        //first take care of special RTF chars
        StringBuilder backslashed = new StringBuilder(input);
        backslashed.Replace(@"\", @"\\");
        backslashed.Replace(@"{", @"\{");
        backslashed.Replace(@"}", @"\}");

        //then convert the string char by char
        StringBuilder sb = new StringBuilder();
        foreach (char character in backslashed.ToString())
        {
            if (character <= 0x7f)
                sb.Append(character);
            else
                sb.Append("\\u" + Convert.ToUInt32(character) + "?");
        }
        return sb.ToString();
    }

Sample

Funciona perfeitamente para mim!Soluções compiladas de:

Como converter uma string em RTF em C#?

Formatar texto em Rich Text Box

Como ocultar o cursor em um RichTextBox?

  1. Crie o texto como um arquivo RTF no wordpad
  2. Crie um controle Rich Text sem bordas e editável = false
  3. Adicione o arquivo RTF ao projeto como um recurso
  4. No Form1_load faça

    meuRtfControl.Rtf = Resource1.MyRtfControlText

AutoRichLabel

      AutoRichLabel with formatted RTF content

Eu estava resolvendo esse problema construindo um UserControl que contém um TransparentRichTextBox isso é somente leitura.O TransparentRichTextBox é um RichTextBox que permite ser transparente:

TransparentRichTextBox.cs:

public class TransparentRichTextBox : RichTextBox
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr LoadLibrary(string lpFileName);

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams prams = base.CreateParams;
            if (TransparentRichTextBox.LoadLibrary("msftedit.dll") != IntPtr.Zero)
            {
                prams.ExStyle |= 0x020; // transparent 
                prams.ClassName = "RICHEDIT50W";
            }
            return prams;
        }
    }
}

O final UserControl funciona como invólucro do TransparentRichTextBox.Infelizmente, tive que limitá-lo a AutoSize do meu jeito, porque o AutoSize do RichTextBox ficou quebrado.

AutoRichLabel.designer.cs:

partial class AutoRichLabel
{
    /// <summary> 
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary> 
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Component Designer generated code

    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.rtb = new TransparentRichTextBox();
        this.SuspendLayout();
        // 
        // rtb
        // 
        this.rtb.BorderStyle = System.Windows.Forms.BorderStyle.None;
        this.rtb.Dock = System.Windows.Forms.DockStyle.Fill;
        this.rtb.Location = new System.Drawing.Point(0, 0);
        this.rtb.Margin = new System.Windows.Forms.Padding(0);
        this.rtb.Name = "rtb";
        this.rtb.ReadOnly = true;
        this.rtb.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
        this.rtb.Size = new System.Drawing.Size(46, 30);
        this.rtb.TabIndex = 0;
        this.rtb.Text = "";
        this.rtb.WordWrap = false;
        this.rtb.ContentsResized += new System.Windows.Forms.ContentsResizedEventHandler(this.rtb_ContentsResized);
        // 
        // AutoRichLabel
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
        this.BackColor = System.Drawing.Color.Transparent;
        this.Controls.Add(this.rtb);
        this.Name = "AutoRichLabel";
        this.Size = new System.Drawing.Size(46, 30);
        this.ResumeLayout(false);

    }

    #endregion

    private TransparentRichTextBox rtb;
}

AutoRichLabel.cs:

/// <summary>
/// <para>An auto sized label with the ability to display text with formattings by using the Rich Text Format.</para>
/// <para>­</para>
/// <para>Short RTF syntax examples: </para>
/// <para>­</para>
/// <para>Paragraph: </para>
/// <para>{\pard This is a paragraph!\par}</para>
/// <para>­</para>
/// <para>Bold / Italic / Underline: </para>
/// <para>\b bold text\b0</para>
/// <para>\i italic text\i0</para>
/// <para>\ul underline text\ul0</para>
/// <para>­</para>
/// <para>Alternate color using color table: </para>
/// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0  is blue.\par</para>
/// <para>­</para>
/// <para>Additional information: </para>
/// <para>Always wrap every text in a paragraph. </para>
/// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
/// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0  is bold.\par)</para>
/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
/// </summary>
public partial class AutoRichLabel : UserControl
{
    /// <summary>
    /// The rich text content. 
    /// <para>­</para>
    /// <para>Short RTF syntax examples: </para>
    /// <para>­</para>
    /// <para>Paragraph: </para>
    /// <para>{\pard This is a paragraph!\par}</para>
    /// <para>­</para>
    /// <para>Bold / Italic / Underline: </para>
    /// <para>\b bold text\b0</para>
    /// <para>\i italic text\i0</para>
    /// <para>\ul underline text\ul0</para>
    /// <para>­</para>
    /// <para>Alternate color using color table: </para>
    /// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0  is blue.\par</para>
    /// <para>­</para>
    /// <para>Additional information: </para>
    /// <para>Always wrap every text in a paragraph. </para>
    /// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
    /// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0  is bold.\par)</para>
    /// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
    /// </summary>
    [Browsable(true)]
    public string RtfContent
    {
        get
        {
            return this.rtb.Rtf;
        }
        set
        {
            this.rtb.WordWrap = false; // to prevent any display bugs, word wrap must be off while changing the rich text content. 
            this.rtb.Rtf = value.StartsWith(@"{\rtf1") ? value : @"{\rtf1" + value + "}"; // Setting the rich text content will trigger the ContentsResized event. 
            this.Fit(); // Override width and height. 
            this.rtb.WordWrap = this.WordWrap; // Set the word wrap back. 
        }
    }

    /// <summary>
    /// Dynamic width of the control. 
    /// </summary>
    [Browsable(false)]
    public new int Width
    {
        get
        {
            return base.Width;
        } 
    }

    /// <summary>
    /// Dynamic height of the control. 
    /// </summary>
    [Browsable(false)]
    public new int Height
    {
        get
        {
            return base.Height;
        }
    }

    /// <summary>
    /// The measured width based on the content. 
    /// </summary>
    public int DesiredWidth { get; private set; }

    /// <summary>
    /// The measured height based on the content. 
    /// </summary>
    public int DesiredHeight { get; private set; }

    /// <summary>
    /// Determines the text will be word wrapped. This is true, when the maximum size has been set. 
    /// </summary>
    public bool WordWrap { get; private set; }

    /// <summary>
    /// Constructor. 
    /// </summary>
    public AutoRichLabel()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Overrides the width and height with the measured width and height
    /// </summary>
    public void Fit()
    {
        base.Width = this.DesiredWidth;
        base.Height = this.DesiredHeight;
    }

    /// <summary>
    /// Will be called when the rich text content of the control changes. 
    /// </summary>
    private void rtb_ContentsResized(object sender, ContentsResizedEventArgs e)
    {
        this.AutoSize = false; // Disable auto size, else it will break everything
        this.WordWrap = this.MaximumSize.Width > 0; // Enable word wrap when the maximum width has been set. 
        this.DesiredWidth = this.rtb.WordWrap ? this.MaximumSize.Width : e.NewRectangle.Width; // Measure width. 
        this.DesiredHeight = this.MaximumSize.Height > 0 && this.MaximumSize.Height < e.NewRectangle.Height ? this.MaximumSize.Height : e.NewRectangle.Height; // Measure height. 
        this.Fit(); // Override width and height. 
    }
}

A sintaxe do formato rich text é bastante simples:

Parágrafo:

{\pard This is a paragraph!\par}

Texto em negrito/itálico/sublinhado:

\b bold text\b0
\i italic text\i0
\ul underline text\ul0

Cor alternativa usando tabela de cores:

{\colortbl ;\red0\green77\blue187;}
{\pard The word \cf1 fish\cf0  is blue.\par

Mas observe:Sempre envolva cada texto em um parágrafo.Além disso, tags diferentes podem ser empilhadas (ou seja, \pard\b\i Bold and Italic\i0\b0\par) e o caractere de espaço atrás de uma tag é ignorado.Então, se você precisar de um espaço atrás dele, insira dois espaços (ou seja, \pard The word \bBOLD\0 is bold.\par).Escapar \ ou { ou }, use um líder \.Para mais informações existe um especificação completa do formato rich text online.

Usando esta sintaxe bastante simples você pode produzir algo como você pode ver na primeira imagem.O conteúdo rich text que foi anexado ao RtfContent propriedade minha AutoRichLabel na primeira imagem estava:

{\colortbl ;\red0\green77\blue187;}
{\pard\b BOLD\b0  \i ITALIC\i0  \ul UNDERLINE\ul0 \\\{\}\par}
{\pard\cf1\b BOLD\b0  \i ITALIC\i0  \ul UNDERLINE\ul0\cf0 \\\{\}\par}

AutoRichLabel with formatted RTF content

Se você deseja ativar a quebra de linha, defina a largura máxima para o tamanho desejado.No entanto, isso fixará a largura na largura máxima, mesmo quando o texto for mais curto.

Divirta-se!

Há um excelente artigo de 2009 no Code Project chamado "Um renderizador HTML profissional que você usará" que implementa algo semelhante ao que o autor da postagem original deseja.

Eu o uso com sucesso em vários projetos nossos.

Solução muito simples:

  1. Adicione 2 rótulos no formulário, LabelA e LabelB
  2. Vá para as propriedades de LabelA e encaixe-o à esquerda.
  3. Vá para as propriedades do LabelB e encaixe-o à esquerda também.
  4. Defina Font como negrito para LabelA .

Agora o LabelB mudará dependendo do comprimento do texto do LabelA.

Isso é tudo.

Eu também estaria interessado em saber se é possível.

Quando não conseguimos encontrar uma solução recorremos ao controle 'SuperLabel' do Component Ones que permite a marcação HTML em um rótulo.

Percebendo que esta é uma questão antiga, a minha resposta é mais para aqueles que, como eu, ainda procuram tais soluções e se deparam com esta questão.

Além do que já foi mencionado, o DevExpress EtiquetaControl é um rótulo que suporta esse comportamento - demonstração aqui.Infelizmente, faz parte de uma biblioteca paga.

Se você está procurando soluções gratuitas, acredito Renderizador HTML é a próxima melhor coisa.

Um FlowLayoutPanel funciona bem para o seu problema.Se você adicionar rótulos ao painel de fluxo e formatar as propriedades de fonte e margem de cada rótulo, poderá ter estilos de fonte diferentes.Solução bastante rápida e fácil de começar a trabalhar.

Sim.Você pode implementar usando HTML Render.Para você ver, clique no link: https://htmlrenderer.codeplex.com/Espero que isso seja útil.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top