473,406 Members | 2,390 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

How to get the TextExtent of a string

Dom
In part of my code, I need to know the rectangle that a string will
fit into, if it is written in a given font and a given Device Context
(DC may be an old term). Back in the days of "C" and Windows 3, you
had to create a DC, Select a Font into the DC, then call
GetTextExtentPoint32, which took the string as an argument. It
returned the rectangle.

I can do this in CSharp by calling the same API functions, but my
guess is that it is done often enough that it should be wrapped up
somewhere. I've looked, can't find it. Any help?

Dom

Aug 15 '07 #1
3 3551
Dom
On Aug 15, 2:17 pm, Dom <dolivas...@gmail.comwrote:
In part of my code, I need to know the rectangle that a string will
fit into, if it is written in a given font and a given Device Context
(DC may be an old term). Back in the days of "C" and Windows 3, you
had to create a DC, Select a Font into the DC, then call
GetTextExtentPoint32, which took the string as an argument. It
returned the rectangle.

I can do this in CSharp by calling the same API functions, but my
guess is that it is done often enough that it should be wrapped up
somewhere. I've looked, can't find it. Any help?

Dom
Son of a ...

I just found VisualStyleRenderer

Aug 15 '07 #2
Sure thing. It's wrapped under the Graphics class, and it's called
MeasureString(...).

Hope this helps.
Saul

"Dom" wrote:
In part of my code, I need to know the rectangle that a string will
fit into, if it is written in a given font and a given Device Context
(DC may be an old term). Back in the days of "C" and Windows 3, you
had to create a DC, Select a Font into the DC, then call
GetTextExtentPoint32, which took the string as an argument. It
returned the rectangle.

I can do this in CSharp by calling the same API functions, but my
guess is that it is done often enough that it should be wrapped up
somewhere. I've looked, can't find it. Any help?

Dom

Aug 15 '07 #3
/// <summary>
/// Summary description for TextTrimming.
/// </summary>
public class TextTrimmer : IDisposable
{
#region Events & Delegates
public delegate void TextTrimmingHandler(object o, TrimmingTextEventArgs
i_args);
public event TextTrimmingHandler TextTrimmed;
#endregion

#region Data members
private Graphics m_graphics = null;
private Control m_Control = null;
private SizeF m_stringMeasure = new SizeF();
private bool m_isTrimmed = false;
private string m_trimmedNewValue = "";
private string m_measuredString = "";
private Font m_measuredFont = null;
#endregion

#region Consts
public const string TRIM_TEXT = "...";
#endregion

#region Properties
public int StringWidth
{
get
{
return (int) m_stringMeasure.Width;
}
}

public bool Trimmed
{
get
{
return m_isTrimmed;
}
}

public int StringHeigth
{
get
{
return (int) m_stringMeasure.Height;
}
}

public string TrimmedString
{
get
{
if( m_trimmedNewValue.Length == 0 )
{
return m_measuredString;
}
return m_trimmedNewValue;
}
}

public string MeasureString
{
get
{
return m_measuredString;
}
}
#endregion

public TextTrimmer(Control i_control)
: this(i_control, i_control.Text, i_control.Font)
{

}

public TextTrimmer(Control i_control, string i_textToMeasure)
: this(i_control, i_textToMeasure, i_control.Font)
{
}

public TextTrimmer(Control i_control, string i_textToMeasure, Font
i_fontToMeasure)
{
m_Control = i_control;

m_graphics = m_Control.CreateGraphics();

m_measuredString = i_textToMeasure;

m_measuredFont = i_fontToMeasure;

m_stringMeasure = m_graphics.MeasureString(m_measuredString,
m_measuredFont);
}

public void Apply()
{
Apply(m_Control.Width, 30);
}

public void Apply(int i_refWidth, int i_assistRefWidth)
{
if( StringWidth == 0 )
{
return;
}

// Add 5 (assummed) pixel because the layout have some unvisible width
which hurt the text value visibility
if (StringWidth + 5 < i_refWidth)
{
return;
}

char[] crArray = m_measuredString.ToCharArray();

int textWidthInPixels = 0;

StringBuilder builder = new StringBuilder();

for (int i = 0; i < crArray.Length; i++)
{
builder.Append(crArray[i].ToString());

textWidthInPixels = (int) (m_graphics.MeasureString(
builder.ToString(),
m_measuredFont).Width);

if (textWidthInPixels >= i_refWidth - i_assistRefWidth)
{
m_isTrimmed = true;

m_trimmedNewValue += TRIM_TEXT;

break;
//m_stringMeasure.Width = textWidthInPixels + 30;
//m_valueTextLength = textWidthInPixels + 30;
}
else
{
m_trimmedNewValue = builder.ToString();
}
}

string oldString = m_measuredString;

m_Control.Text = m_trimmedNewValue;

OnTextTrimmed( oldString, m_trimmedNewValue );
}
protected void OnTextTrimmed(string i_oldString, string i_newTrimmedString)
{
if( TextTrimmed != null )
{
TextTrimmed(this,
new TrimmingTextEventArgs(m_Control,
i_oldString,
i_newTrimmedString));
}
}
#region IDisposable Members

public void Dispose()
{
if( m_graphics != null)
{
m_graphics.Dispose();
}

GC.SuppressFinalize(this);
}

#endregion
}

#region public class TrimmingTextEventArgs : EventArgs
public class TrimmingTextEventArgs : EventArgs
{
private string m_allText;
private string m_trimmedText;
private Control m_refControl;

public string AllText
{
get
{
return m_allText;
}
}
public string TrimmedText
{
get
{
return m_trimmedText;
}
}
public Control RefControl
{
get
{
return m_refControl;
}
}
public TrimmingTextEventArgs(Control i_refControl, string i_allText,
string i_trimmedText)
{
m_refControl = i_refControl;
m_allText = i_allText;
m_trimmedText = i_trimmedText;
}
}
#endregion

Enjoy.
--
Sincerely
Yaron Karni
http://dotnetbible.blogspot.com/
"Dom" wrote:
On Aug 15, 2:17 pm, Dom <dolivas...@gmail.comwrote:
In part of my code, I need to know the rectangle that a string will
fit into, if it is written in a given font and a given Device Context
(DC may be an old term). Back in the days of "C" and Windows 3, you
had to create a DC, Select a Font into the DC, then call
GetTextExtentPoint32, which took the string as an argument. It
returned the rectangle.

I can do this in CSharp by calling the same API functions, but my
guess is that it is done often enough that it should be wrapped up
somewhere. I've looked, can't find it. Any help?

Dom

Son of a ...

I just found VisualStyleRenderer

Aug 17 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site......
5
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it...
9
by: John F Dutcher | last post by:
I use code like the following to retrieve fields from a form: recd = recd.append(string.ljust(form.getfirst("lname",' '),15)) recd.append(string.ljust(form.getfirst("fname",' '),15)) etc.,...
9
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people...
10
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is...
37
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie,...
2
by: Andrew | last post by:
I have written two classes : a String Class based on the book " C++ in 21 days " and a GenericIpClass listed below : file GenericStringClass.h // Generic String class
2
by: s | last post by:
I'm getting compile errors on the following code: <code> #include <iostream> #include <fstream> #include <list> #include <string> using namespace std;
11
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while(...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.