Calculating size of CheckBox based on Text

D

Dean

I have a checkbox where I want to programmatically set the text. The
checkbox sits on top of a group box, so I need to set the Size property of
the checkbox properly, based on the length of the checkbox Text (plus an
allowance for the size of the box itself). (Otherwise, if the size is too
small the text will wrap, and if it's too big a larger portion of the
groupbox's line will be covered up.) I want the text to look like normal
group box text - the line of
the group box starts up again as the text ends.

I am currently doing this like so:

private CheckBox chk = new CheckBox();
private Graphics gdi = Graphics.FromHwnd(chk.Handle);
chk.Width = (int)gdi.MeasureString(chk.Text, chk.Font).Width + 20;

Unfortunately, this only does a "so-so" job. There is a noticable gap after
the text and before the groupbox line begins. The longer the text is, the
larger this gap becomes. If I add less than 20 on to the calculated width,
the text wraps, and there is still a noticable gap before the groupbox line
starts up.

Is there a better way for me to do this? I'd really appreciate any help you
can offer.

Thanks
 
M

Morten Wennevik

Hi Dean,

MeasureString is an approximatly measurement. If you need exact size you
need to use MeasureCharacterRanges.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top