Simple Text Extent Question

D

dvestal

Font font = new Font("Courier New", 8);
Graphics g = listBox1.CreateGraphics();
int width1 = g.MeasureString(" ", font).Width; // a space
int width2 = g.MeasureString("S", font).Width;

width1 does not equal width2. Since it's a monospace font, why not?

That's the question boiled down to its essence. The background is
this: I'm trying to display a tooltip based on the character the mouse
is hovering over in a DataGridView. For unrelated reasons, I'm not
using the built-in tooltip support, and I have implemented the
CellMouseMove event for the datagridview as follows (simplified):

private ToolTip tt = new ToolTip();
private Font f = new Font("Courier New", 8);

private void grid_CellMouseMove(object sender,
DataGridViewCellMouseEventArgs e)
{
Graphics g = grid.CreateGraphics();

// Since we're using a monospace font, one character should have
// the same width of as all the others, but it isn't working that
way.
// Why is that?
float charWidth = g.MeasureString("1", f).Width;

tt.SetToolTip(grid, "Hovering over character " + (int)
(e.Location.X / charWidth));
}
 
L

Laura T.

MeasureString does not work very well with single characters, as it takes in
account aliasing, kerning, extras and many other things that can fool it.

You might try TextRenderer.Measure, or handle a special case when you have
just a blank to use another char, or btter not to measure single chars but
at least two chars.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top