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.
Use Graphics.MeasureString instead. The result is SizeF and not Size like the TextRenderer's method returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With