RichTextBox SelectionTab problem

  • Thread starter Thread starter Kaki Cheung
  • Start date Start date
K

Kaki Cheung

Hi all. I've seen examples on how to measure average
character width with StringFormat.GenericTypographic and
how to set the SelectionTab array, but the problem is, even
with fixed size font (Courier New in my case), the tab
width is off by 1 or 2 pixels, depending on font size.

Seems to me it's not rounding problem... Anyone has a
better idea?

Here's my code:

public static void SetTabSize(RichTextBox rtb, int nChar) {
int tabsz = (int)((aveCharWidth(rtb.CreateGraphics(),
rtb.Font) * (Char));
System.Diagnostics.Debug.WriteLine(tabsz);
int[] tabs = new int[32];
tabs[0] = tabsz;
for(int i=1; i<tabs.Length; i++) {
tabs = tabs[i-1] + tabsz;
}
rtb.SelectionTabs = tabs;
}

private static float aveCharWidth(Graphics g, Font f) {
string str =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
return g.MeasureString(str, f, 0,
StringFormat.GenericTypographic).Width / str.Length;
}
 
Its probably because the rich textbox uses gdi for rendering - not gdi+.
You're measuring the string using gdi+, which is definitely going to be
different then if you were to measure the string using gdi (e.g.
GetTextExtentPoint32).
 
Back
Top