Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine if a form's text will fit in?

Is there a way to determine if the form's text property will fit in the top bar using the form's current width (or if it will be truncated with "...")?

enter image description here

like image 381
Mierzen Avatar asked May 16 '15 13:05

Mierzen


1 Answers

You might take a look into TextRenderer.MeasureText().

To calculate the width of a caption text use this snippet:

var width = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width;

You could use the size of your Form, subtract a fixed value for the icon (if visible) and the buttons on the top right (depends on the OS version and on the visible state of the [Minimize] [Maximize] buttons) and check if it is still positive. This might not give you a perfectly accurate result, but it is probably the simplest approximation.

So far, this method seems to calculate a pretty accurate approximation:

/// <summary>
/// Calculates an approximation of the available caption width
/// Depends on OS and theme
/// </summary>
/// <returns>Width</returns>
private int CalcAvaliableCaptionWidth()
{
    return
    // Form width
    Width
    // Icon
    - (Icon == null ? 0 : Icon.Width)
    // Minimize button (26 on Win8)
    - (MinimizeBox ? SystemInformation.CaptionButtonSize.Width : 0)
    // Maximize button (26 on Win8)
    - (MaximizeBox ? SystemInformation.CaptionButtonSize.Width : 0)
    // Close button (45 on Win8)
    - SystemInformation.CaptionButtonSize.Width;
}

You might try my little verification WinForm application

verification WinForm application

Source code: https://gist.github.com/CodeZombieCH/b9def0b0d9c41a98593a

Thanks to @Plutonix for the hint to SystemInformation.CaptionButtonSize.

like image 121
CodeZombie Avatar answered Oct 11 '22 11:10

CodeZombie