Emad Khalil Emad Khalil - 1 year ago 44
C# Question

How can I make the text of checkbox wraps automatically with changing form width?

In windows forms I have checkbox list that contains long text, the form is re-sizable..

can I make the text wraps automatically in run-time according to the form width ?

Answer Source

I tried many approaches but at last this one worked after a lot of researches:-

simply I used two events to detect size change of the panel contains the controls then I adjusted the controls accordingly..

first event is LayoutEventHandler, second event for detecting resolution change

in these events:-

1- get the panel width considering the resolution (lower accepted resolution is 1024x768)

  Rectangle resolution = Screen.PrimaryScreen.Bounds;
  int panelWidth *= (int)Math.Floor((double)resolution.Width / 1024);

2- loop on all controls and adjust the control width to fit the panel width (i subtracted 10 pixels for vertical scroll width), then I got the control height from MeasureString function which takes the control text, the font and control width, and return the control size.

(i.e. I multiplied the height with a roughly factor "1.25" to overcome line height and padding)

  foreach (var control in controls)
      if (control is RadioButton || control is CheckBox)
             control.Width = panelWidth - 10;

             Font fontUsed = control.Font;
             using (Graphics g = control.CreateGraphics())
               SizeF size = g.MeasureString(control.Text, fontUsed, control.Width);
              control.Height = (int)Math.Ceiling(size.Height * 1.25);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download