Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get the exact text margins used by TextRenderer
    text
    copied!<p><code>System.Windows.Forms.TextRenderer.DrawText</code> method renders formatted text with or without left and right padding depending on the value of the <code>flags</code> parameter:</p> <ul> <li><code>TextFormatFlags.NoPadding</code> - fits the text tightly into the bounding box,</li> <li><code>TextFormatFlags.GlyphOverhangPadding</code> - adds some left and right margins,</li> <li><code>TextFormatFlags.LeftAndRightPadding</code> - adds even bigger margins.</li> </ul> <p>Now, my question is <strong>how can I get the exact amount of padding (left and right) added by <code>DrawText</code> to the text</strong> for a given device context, string, font etc?</p> <p>I've dug into .NET 4 with .NET Reflector and found that TextRenderer calculates "overhang padding" which is 1/6 of the font's height and then multiplies this value to calculate left and right margins using these coefficients:</p> <ul> <li>left 1.0, right 1.5 for <code>TextFormatFlags.GlyphOverhangPadding</code>,</li> <li>left 2.0, right 2.5 for <code>TextFormatFlags.LeftAndRightPadding</code>.</li> </ul> <p>The resulting values are rounded up and passed to the <code>DrawTextExA</code> or <code>DrawTextExW</code> native API functions. It's difficult to recreate this process because font's height is taken not from <code>System.Drawing.Font</code> but from <code>System.Windows.Forms.Internal.WindowsFont</code> and these classes return different values for the same font. And a lot of other internal BCL classes from the <code>System.Windows.Forms.Internal</code> namespace are involved. Decompiling all of them and reusing their code in my app is not an option, because that would be a serious .NET implementation dependency. That's why I need to know if there is some public API in WinForms or at least which Windows functions I can use to get the values of left and right margins.</p> <hr> <p><strong>Note:</strong> I've tried to <code>TextRenderer.MeasureText</code> with and without padding and compare the results but that gave me only the sum of left and right margins and I need them separately.</p> <hr> <p><strong>Note 2:</strong> In case you wonder why I need this: I want to draw one string with multiple fonts/colors. That involves calling <code>DrawText</code> once for every uniformly formatted substring with <code>NoPadding</code> option (so that the text doesn't spread) but I also want to add manually normal <code>GlyphOverhangPadding</code> at the very beginning and very end of the whole multi-format text.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload