1

My initial instinct is to get the current DpiY setting of the system via a Graphics instance, but I cannot figure out how to get one.

Spellunking through Reflector I see that Microsoft manages it using unsafe code:

IntPtr dC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
    using (Graphics graphics = Graphics.FromHdcInternal(dC))
    {
        float num = graphics.DpiY;
    }
}

What is the managed equivalent way to construct a Graphics when i don't have a graphics?

I tried:

using (Graphics g = Graphics.FromHdc(IntPtr.Zero))
{
    return font.GetHeight(g.DpiY);
}

But that throws a Value cannot be null exception.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
  • Usually, when I get to the end of my question and figure out what my *real question is*, I change my title. Please review my edit to make sure I didn't muck up your question. –  Jan 17 '12 at 14:35
  • @Will That was sort of the point in my original question. i'm not *always* interested in the font size (e.g. control size, image size, scaling amount). i was afraid that someone might short-circuit the question, and try to use `MeasureText` to get the font height. People tend to confuse question with applicability. i've tried omitting rationale, having just my question. But people refuse to answer it without knowing *why* i want to do something. i've had thorough examples of *why*, then you have John Saunders downvote because he's grumpy (http://stackoverflow.com/q/8141795/12597) – Ian Boyd Jan 17 '12 at 16:47
  • @Will Here's another good example of the problem. A guy asked the exact question i had ***LINQ where or filter c#*** (http://stackoverflow.com/questions/5954965/linq-where-or-filter-c-sharp). The answers cheated the question, answering instead the example. Today i have the exact same question, but the existing answers do not answer the question. i have to construct the exact same question (with the words in the title rearranged to look sufficiently different ***LINQ filter where or*** (http://stackoverflow.com/questions/8900131/linq-filter-where-or). – Ian Boyd Jan 17 '12 at 19:05

1 Answers1

1

You can try using the TextRendering method which does not use a Graphics object:

int textHeight = TextRenderer.MeasureText("Text", this.Font).Height;

Or if need be, you can make your own quick Graphic:

float textHeight;
using (Bitmap b = new Bitmap(1,1))
using (Graphics g = Graphics.FromImage(b)) {
  textHeight = this.Font.GetHeight(g.DpiY);
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • i was concerned that a Bitmap's resolution is not guaranteed to be created at the current system dpi setting (i.e. a lot of drawing systems create a graphic at 72 dpi). But it seems to match the system resolution upon `Bitmap` creation. – Ian Boyd Jan 17 '12 at 19:01