I’m trying to draw a margin at 80 characters in my TextBox subclass. Here is my code:
class FooTextBox : TextBox
{
...
void UpdateMarginPosition()
{
using (Graphics graphics = CreateGraphics()) {
int charWidth = TextRenderer.MeasureText(graphics, "M", Font,
ClientSize, TextFormatFlags.NoPadding).Width;
const int LeftMargin = 2;
margin.Left = charWidth * 80 + LeftMargin;
}
}
}
This works fine for certain fonts at certain sizes (e.g., Courier New at size 10):
But with other fonts this turns out to be slightly inaccurate. Here is a screenshot with Consolas at size 12, for example:
As you can see, the line cuts through the 0, when instead it should be to the right of the 0.
EDIT:
I forgot to mention that ‘margin’ is a WinForms.Label.


Okay, I solved the problem. I had to get the left margin of the TextBox by sending EM_GETMARGINS (rather than just assuming that the left margin is 2, which works for only some fonts/sizes), and I had to do this after
base.OnFontChanged(e);in my OnFontChanged override. Thanks, all, for the assistance.