http://www.developer.com/net/cplus/article.php/3411421/Managed-Extensions-Measuring-Strings.htm
Welcome to this week's installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer demonstrates how to perform a practical .NET programming task using either C# or Managed C++ Extensions.
A recent client of mine wanted text to be displayed in a Label (static) control only if the text could fit. If the text could not fit into the Label, the user was to see a string indicating that the text was too long and they could double click the item to drill down into the details of the value (which displayed another dialog). Using .NET, this turned out to be much easier than I first anticipated.
I've created a simple Managed Extensions demo to illustrate how to do this. Here's a figure of that application being run a few times:
As you can see, the code is tested by entering text into a multi-line TextBox (edit) control and then clicking the Display button. If the text fits nicely into the Label control, it's displayed. If not, the text "Too large" is displayed instead.
This is accomplished by performing the following steps:
Here's how that code would look (copied from the article's demo):
The last two things to point out are:
To download the accompanying source code for this article, click here. The founder of the Archer Consulting Group (ACG), Tom Archer has been the project lead on three award-winning applications and is a best-selling author of 10 programming books as well as countless magazine and online articles.
Managed Extensions: Measuring Strings
September 22, 2004
private: System::Void button1_Click(System::Object * sender, System::EventArgs * e)
{
Graphics* g = label1->CreateGraphics();
SizeF size = g->MeasureString(textBox1->Text,label1->Font);
if (size.Width < label1->Width
&& size.Height < label1->Height) // fits
{
label1->Text = textBox1->Text;
}
else // doesn't fit
{
label1->Text = S"Too large";
}
}
Download the Code
About the Author