locked
label font and style RRS feed

  • Question

  • Is there a way to change the font style on only part of a label; i.e. is it possible for me to code a windows form label like so:

         label1.Text = "Only this part is bold";

    and add some sort of style code to have it render like so:

         Only this part is bold

    Tuesday, December 5, 2006 5:24 PM

Answers

  • I doubt there's a control out there that would do this.  It would be pretty awkward to specify the desired formatting.  Instead, you could just paint directly to the form to make it look like a label.  For example:

        private void Form1_Paint(object sender, PaintEventArgs e) {
          Font bold = new Font(this.Font, FontStyle.Bold);
          string[] text = new string[] { "Only ", "this part", " is bold" };
          TextFormatFlags fmt = TextFormatFlags.NoClipping | TextFormatFlags.NoPadding;
          Size part1 = TextRenderer.MeasureText(e.Graphics, text[0], this.Font, this.ClientSize, fmt);
          Size part2 = TextRenderer.MeasureText(e.Graphics, text[1], bold, this.ClientSize, fmt);
          TextRenderer.DrawText(e.Graphics, text[0], this.Font, new Point(20, 10), this.ForeColor);
          TextRenderer.DrawText(e.Graphics, text[1], bold, new Point(20+part1.Width, 10), this.ForeColor);
          TextRenderer.DrawText(e.Graphics, text[2], this.Font, new Point(20+part1.Width+part2.Width, 10), this.ForeColor);
        }

    Tuesday, December 5, 2006 6:24 PM

All replies

  • Unfortunately you can't do that!, you can create your own label control or use a read-only rich-textbox.
    Tuesday, December 5, 2006 5:34 PM
  • Thank you for your response.

    Does anyone know of a third party label control that will allow for formatting or can maybe point me in the right direction as to how to go about creating one?

    Tuesday, December 5, 2006 5:43 PM
  • I doubt there's a control out there that would do this.  It would be pretty awkward to specify the desired formatting.  Instead, you could just paint directly to the form to make it look like a label.  For example:

        private void Form1_Paint(object sender, PaintEventArgs e) {
          Font bold = new Font(this.Font, FontStyle.Bold);
          string[] text = new string[] { "Only ", "this part", " is bold" };
          TextFormatFlags fmt = TextFormatFlags.NoClipping | TextFormatFlags.NoPadding;
          Size part1 = TextRenderer.MeasureText(e.Graphics, text[0], this.Font, this.ClientSize, fmt);
          Size part2 = TextRenderer.MeasureText(e.Graphics, text[1], bold, this.ClientSize, fmt);
          TextRenderer.DrawText(e.Graphics, text[0], this.Font, new Point(20, 10), this.ForeColor);
          TextRenderer.DrawText(e.Graphics, text[1], bold, new Point(20+part1.Width, 10), this.ForeColor);
          TextRenderer.DrawText(e.Graphics, text[2], this.Font, new Point(20+part1.Width+part2.Width, 10), this.ForeColor);
        }

    Tuesday, December 5, 2006 6:24 PM