Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Text width?

How can I get the width of a string in a control such as textbox or listbox?
In VB6.0 I could use a form as reference to get it:
lString = frmMain.TextWidth(txtFile.text)
I checked the members of Form in .Net C#, there is no TextWidth method.
D. Chu
[280 byte] By [David Chu] at [2007-11-9 18:47:01]
# 1 Re: Text width?
It looks like that there is no answer for this problem yet. I tried to do
some search on web. One way to get the width of a string is by using MeasureString
method of Graphics:

float fTextWidth = g.MeasureString("my string", text1.Font);

However, the problem is that I want to get the width of string in a TextBox
or ListBox, and I don't have Graphics availble.

Anyway, I tried to create a graphics object from a picture box like this:

Graphics g = Graphics.FromHdc( pic1.Handle);

I failed to get g (maybe it is empty?). Anyway, why .Net make things so complicated?
Is there other way to get the width of a string in TextBox or ListBox? or
Measure it by the control's font?

D. Chu
David Chu at 2007-11-11 22:00:31 >
# 2 Re: Text width?
Could you try some thing like

lString = frmMain.txtFile.Text.Length

"David Chu" <chud@hotmail.com> wrote in message
news:3e8330be$1@tnews.web.dev-archive.com...
>
> How can I get the width of a string in a control such as textbox or
listbox?
> In VB6.0 I could use a form as reference to get it:
>
> lString = frmMain.TextWidth(txtFile.text)
>
> I checked the members of Form in .Net C#, there is no TextWidth method.
>
> D. Chu
Michael Gautier at 2007-11-11 22:01:36 >
# 3 Re: Text width?
"Michael Gautier" <gautier_michael@hotmail.com> wrote:
>Could you try some thing like
>
>lString = frmMain.txtFile.Text.Length
>
>

This is not I want. Text.Length will return the number of characters in the
textbox, same for TextLength. What I want is the width of text in the textbox,
and use it to compare against the width of the textbox's width (too long
or not).

D. Chu
David Chu at 2007-11-11 22:02:34 >
# 4 Re: Text width?
Try using:

Graphics g = Graphics.FromHandle(form.Handle); // I think this is the
right call...

and then use g.MeasureString() to figure out how wide it will be.

--
Visit the C# product team at http://www.csharp.net

This posting is provided "AS IS" with no warranties, and confers no rights.

"David Chu" <chud@hotmail.com> wrote in message
news:3e89bb37$1@tnews.web.dev-archive.com...
>
> "Michael Gautier" <gautier_michael@hotmail.com> wrote:
> >Could you try some thing like
> >
> >lString = frmMain.txtFile.Text.Length
> >
> >
>
> This is not I want. Text.Length will return the number of characters in
the
> textbox, same for TextLength. What I want is the width of text in the
textbox,
> and use it to compare against the width of the textbox's width (too long
> or not).
>
> D. Chu
Eric Gunnerson at 2007-11-11 22:03:35 >
# 5 Re: Text width?
Windows Forms Controls expose a CreateGraphics property that returns a
Graphics object you can use to measure the width of the string. Here's an
example form.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace MeasureTextWidth
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.ComboBox comboFont;
private System.Windows.Forms.ComboBox comboSize;
private bool loading=false;
private System.Windows.Forms.Label lblWidth;
private System.Windows.Forms.Label lblHeight;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.comboFont = new System.Windows.Forms.ComboBox();
this.comboSize = new System.Windows.Forms.ComboBox();
this.lblWidth = new System.Windows.Forms.Label();
this.lblHeight = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Font = new System.Drawing.Font("Arial", 20F,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,
((System.Byte)(0)));
this.textBox1.Location = new System.Drawing.Point(24, 32);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(208, 38);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "This is a string";
this.textBox1.TextChanged += new
System.EventHandler(this.textBox1_TextChanged);
//
// comboFont
//
this.comboFont.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboFont.Location = new System.Drawing.Point(24, 213);
this.comboFont.Name = "comboFont";
this.comboFont.Size = new System.Drawing.Size(232, 21);
this.comboFont.TabIndex = 2;
this.comboFont.SelectedIndexChanged += new
System.EventHandler(this.comboFont_SelectedIndexChanged);
//
// comboSize
//
this.comboSize.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboSize.Location = new System.Drawing.Point(288, 213);
this.comboSize.Name = "comboSize";
this.comboSize.Size = new System.Drawing.Size(80, 21);
this.comboSize.TabIndex = 3;
this.comboSize.SelectedIndexChanged += new
System.EventHandler(this.comboSize_SelectedIndexChanged);
//
// lblWidth
//
this.lblWidth.Location = new System.Drawing.Point(253, 40);
this.lblWidth.Name = "lblWidth";
this.lblWidth.Size = new System.Drawing.Size(72, 24);
this.lblWidth.TabIndex = 4;
//
// lblHeight
//
this.lblHeight.Location = new System.Drawing.Point(338, 40);
this.lblHeight.Name = "lblHeight";
this.lblHeight.Size = new System.Drawing.Size(72, 24);
this.lblHeight.TabIndex = 5;
//
// label1
//
this.label1.Location = new System.Drawing.Point(253, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(48, 16);
this.label1.TabIndex = 6;
this.label1.Text = "Width";
//
// label2
//
this.label2.Location = new System.Drawing.Point(338, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 16);
this.label2.TabIndex = 7;
this.label2.Text = "Height";
//
// label3
//
this.label3.Location = new System.Drawing.Point(24, 192);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(184, 16);
this.label3.TabIndex = 8;
this.label3.Text = "Font Family";
//
// label4
//
this.label4.Location = new System.Drawing.Point(288, 192);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(64, 16);
this.label4.TabIndex = 9;
this.label4.Text = "Font Size";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(424, 270);
this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.label4,

this.label3,

this.label2,

this.label1,

this.lblHeight,

this.lblWidth,

this.comboSize,

this.comboFont,

this.textBox1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e)
{

}

private void Form1_Load(object sender, System.EventArgs e)
{
Font startFont = this.textBox1.Font;
loading=true;
this.textBox1.Text = "This is a string.";
System.Drawing.Text.InstalledFontCollection fonts = new
System.Drawing.Text.InstalledFontCollection();
foreach(FontFamily f in fonts.Families)
{

if (f.Name == startFont.FontFamily.Name)
{
int index= this.comboFont.Items.Add(f.Name);
this.comboFont.SelectedIndex=index;
}
else
{
try
{
this.textBox1.Font = new Font(f.Name,
10,FontStyle.Regular,GraphicsUnit.Point);
this.comboFont.Items.Add(f.Name);
}
catch
{
// some fonts don't display in regular style
}
}
}
this.textBox1.Font = startFont;
for(int i=7; i <= 50; i++)
{
if (i == this.textBox1.Font.SizeInPoints)
{
int index= this.comboSize.Items.Add(i.ToString());
this.comboSize.SelectedIndex=index;
}
else
{
this.comboSize.Items.Add(i.ToString());
}
}
loading=false;
}

private void comboFont_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (loading) {return;}
setFont();
updateSizeLabels();
}

private void setFont()
{
try
{
string familyName = (string) this.comboFont.SelectedItem;
float fontSize = float.Parse((string) comboSize.SelectedItem);
Font f = new
Font(familyName,fontSize,FontStyle.Regular,GraphicsUnit.Point);
this.textBox1.Font = f;
}
catch (Exception ex)
{
MessageBox.Show("Could not set the font based on the font
family and size selected." + System.Environment.NewLine + "Error: " +
ex.Message);
}
}
private void comboSize_SelectedIndexChanged(object sender,
System.EventArgs e)
{
if (loading) {return;}
setFont();
updateSizeLabels();
}

private void updateSizeLabels()
{
Graphics g = this.textBox1.CreateGraphics();
string s = this.textBox1.Text;
SizeF result = g.MeasureString(s,this.textBox1.Font);
lblWidth.Text = result.Width.ToString();
lblHeight.Text = result.Height.ToString();
g.Dispose();
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
updateSizeLabels();
}
}
}

"David Chu" <chud@hotmail.com> wrote in message
news:3e8330be$1@tnews.web.dev-archive.com...
>
> How can I get the width of a string in a control such as textbox or
listbox?
> In VB6.0 I could use a form as reference to get it:
>
> lString = frmMain.TextWidth(txtFile.text)
>
> I checked the members of Form in .Net C#, there is no TextWidth method.
>
> D. Chu
Russell Jones at 2007-11-11 22:04:39 >
# 6 Re: Text width?
The problem of this solution is that in case the font in a textbox is different
from the font in a form, the measurement would not be correct. I found another
very good solution. I can create a Label with AutoSize = true. Then set the
label's font to the textbox font. The width of the label will be the correct
length!

D. Chu

"Eric Gunnerson" <ericgu_nospam@microsoft.nospam.com> wrote:
>Try using:
>
>Graphics g = Graphics.FromHandle(form.Handle); // I think this is
the
>right call...
>
>and then use g.MeasureString() to figure out how wide it will be.
>
>--
>Visit the C# product team at http://www.csharp.net
>
>This posting is provided "AS IS" with no warranties, and confers no rights.
>
>"David Chu" <chud@hotmail.com> wrote in message
>news:3e89bb37$1@tnews.web.dev-archive.com...
>>
>> "Michael Gautier" <gautier_michael@hotmail.com> wrote:
>> >Could you try some thing like
>> >
>> >lString = frmMain.txtFile.Text.Length
>> >
>> >
>>
>> This is not I want. Text.Length will return the number of characters in
>the
>> textbox, same for TextLength. What I want is the width of text in the
>textbox,
>> and use it to compare against the width of the textbox's width (too long
>> or not).
>>
>> D. Chu
>
>
David Chu at 2007-11-11 22:05:36 >
# 7 Re: Text width?
You can pass the font of the textbox into MeasureString().

--
Visit the C# product team at http://www.csharp.net

This posting is provided "AS IS" with no warranties, and confers no rights.

"David Chu" <chud@hotmail.com> wrote in message
news:3e8b25cb$1@tnews.web.dev-archive.com...
>
> The problem of this solution is that in case the font in a textbox is
different
> from the font in a form, the measurement would not be correct. I found
another
> very good solution. I can create a Label with AutoSize = true. Then set
the
> label's font to the textbox font. The width of the label will be the
correct
> length!
>
> D. Chu
>
> "Eric Gunnerson" <ericgu_nospam@microsoft.nospam.com> wrote:
> >Try using:
> >
> >Graphics g = Graphics.FromHandle(form.Handle); // I think this is
> the
> >right call...
> >
> >and then use g.MeasureString() to figure out how wide it will be.
> >
> >--
> >Visit the C# product team at http://www.csharp.net
> >
> >This posting is provided "AS IS" with no warranties, and confers no
rights.
> >
> >"David Chu" <chud@hotmail.com> wrote in message
> >news:3e89bb37$1@tnews.web.dev-archive.com...
> >>
> >> "Michael Gautier" <gautier_michael@hotmail.com> wrote:
> >> >Could you try some thing like
> >> >
> >> >lString = frmMain.txtFile.Text.Length
> >> >
> >> >
> >>
> >> This is not I want. Text.Length will return the number of characters in
> >the
> >> textbox, same for TextLength. What I want is the width of text in the
> >textbox,
> >> and use it to compare against the width of the textbox's width (too
long
> >> or not).
> >>
> >> D. Chu
> >
> >
>
Eric Gunnerson at 2007-11-11 22:06:40 >
# 8 Re: Text width?
Thanks for all the great tips, especially the Russell's one. It solved the
program to get a graphics for a control. My intention to measure the width
of a string is to measure if a string in a control (such as text box, label,
combo, list...) is too large or not. This means the text may exceed the width
or height of the control.

By using graphics, it looks like that it can only measure the width of a
string. Although it can measure the heighth, you can't set the width of a
graphics object so that the string will wrap. Therefore, a dynamic label
with auto-size will be best solution. If it is one line, I can use the label
to measure the width of a string. If it is the case of muti-lines, I can
set the width of label to the width of control, then measure the height.

D. Chu

"Russell Jones" <arj1@nospam.northstate.net> wrote:
>Windows Forms Controls expose a CreateGraphics property that returns a
>Graphics object you can use to measure the width of the string. Here's an
>example form.
> ...
> private void updateSizeLabels()
> {
> Graphics g = this.textBox1.CreateGraphics();
> string s = this.textBox1.Text;
> SizeF result = g.MeasureString(s,this.textBox1.Font);
> lblWidth.Text = result.Width.ToString();
> lblHeight.Text = result.Height.ToString();
> g.Dispose();
> }
> private void textBox1_TextChanged(object sender, System.EventArgs
e)
> {
> updateSizeLabels();
> }
David Chu at 2007-11-11 22:07:39 >