S h o r t S t o r i e s

// Tales from software development

Determining the size required to display text: TextRenderer.MeasureText()

leave a comment »

One of the limitations of the .NET NotifyIcon class’s ShowBalloonTip() method is that there is a limit to the length of text that can be displayed. It’s great for a short warning message but not suitable for a long list of errors.

I’ve just written a tray application that connects to a Windows Service and polls for error messages. Once there are more than four or five error messages, using the ShowBalloonTip() method isn’t appropriate to display these messages so I wrote created a form that mimics the BalloonTip window to some extent but allows more text to be displayed.

As I didn’t want to use scrollbars, I needed to determine how much space is required to display the text and then resize the form and its controls appropriately.

After a bit of searching I found that the System.Windows.Forms namespace contains the TextRenderer class that implements the MeasureText() method. This returns a Size instance indicating the size of the rendered text for the specified Graphics context, text, and Font.

It took a bit of testing to realise that you also need to indicate that text lines can be broken if this is required. Otherwise, regardless of whether the specified Graphics context is not wide enough, the MeasureText() will not wrap or break lines. It will however correctly return the required width even though this is wider than the specific Graphics context.

As an example, my form uses a Label control called MessagesLabel to display the text and this is the call to MeasureText() used to determine the height that the control needs to be to display the text without changing the width of the control:

// Determine how much space the message text requires.
Size textSize = TextRenderer.MeasureText(this.MessagesLabel.CreateGraphics(), this.MessagesLabel.Text, this.MessagesLabel.Font, this.MessagesLabel.Size, TextFormatFlags.WordBreak);

// Adjust the height of the form to accommodate the text to be displayed.
int topMargin = this.MessagesLabel.Top;
int bottomMargin = this.ClientRectangle.Size.Height - this.MessagesLabel.Top - this.MessagesLabel.Height;
int requiredHeight = topMargin + bottomMargin + textSize.Height;




Written by Sea Monkey

January 16, 2017 at 8:00 pm

Posted in Development

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: