Change Label font by CheckBoxes : CheckBox « GUI Windows Forms « C# / CSharp Tutorial






Change Label font by CheckBoxes
using System;
using System.Drawing;
using System.Windows.Forms;

public class LabelFontChangedByCheckBoxes : Form
{
  Label lbl;
  Panel pnl;
  FontStyle[] theStyles;

  public LabelFontChangedByCheckBoxes()
  {
    Size = new Size(300,250);

    lbl = new Label();
    lbl.Parent = this;
    lbl.Text = "test";
    lbl.Location = new Point(0,0);
    lbl.AutoSize = true;
    lbl.BorderStyle = BorderStyle.Fixed3D;
    int yDelta = lbl.Height + 10;
    
    FontStyle theEnum = new FontStyle();
    theStyles = (FontStyle[])Enum.GetValues(theEnum.GetType());

    pnl = new Panel();
    pnl.Parent = this;
    pnl.Location = new Point(0, yDelta );
    pnl.Size = new Size(150, (theStyles.Length + 1) * yDelta);
    pnl.BorderStyle = BorderStyle.FixedSingle;


    int i = 1;
    CheckBox cb;
    foreach (FontStyle style in theStyles)
    {
      cb = new CheckBox();
      cb.Parent = pnl;
      cb.Location = new Point(25, (yDelta * (i - 1)) + 10);
      cb.Size = new Size(75,20);
      cb.Text = style.ToString();
      cb.Tag = style;
      cb.CheckedChanged += new System.EventHandler(cb_CheckedChanged);
      if (cb.Text == "Regular")
        cb.Checked = true;
      i++;
    }
  }

  static void Main() 
  {
    Application.Run(new LabelFontChangedByCheckBoxes());
  }

  private void cb_CheckedChanged(object sender, EventArgs e)
  {
    FontStyle fs = 0;
    for (int i = 0; i < pnl.Controls.Count; i++)
    {
      CheckBox cb = (CheckBox)pnl.Controls[i];
      if (cb.Checked)
        fs |= (FontStyle)cb.Tag;

      if (((CheckBox)pnl.Controls[i]).Checked)
        fs |= (FontStyle)((CheckBox)pnl.Controls[i]).Tag;
    }
    lbl.Font = new Font(lbl.Font, fs);
  }
}








23.9.CheckBox
23.9.1.Change Label font by CheckBoxesChange Label font by CheckBoxes
23.9.2.Add CheckBox to a FormAdd CheckBox to a Form
23.9.3.CheckedChanged event for CheckBox