My blog has moved! Redirecting…

You should be automatically redirected. If not, visit http://www.digitalfugu.com/blog/ and update your bookmarks.

Monday, October 01, 2007

Detect Desktop DPI Settings

Our application was working great. We were using GDI+ to draw custom windows. I've now fought more with GDI+ and half know more than I ever wanted to know about window drawing X_x. I had thought that I would never have to touch that code again for a long time. Things were great until our awesome QA Army of One decided to change from their default resolution of 96 dpi to 120 dpi and then to old school 72 dpi settings "just to see" and did we ever see! There were big black holes all over the place, text was getting cut off and our image banners were all the wrong size plus they were not crisp and clear.

We needed to check for dpi settings and initialize our custom window drawing routines accordingly. I was hoping to heaven that someone at the Microsoft .NET Framework development team had thought of something for that. My prayers were answered by the DpiX and DpiY properties of the System.Drawing.Graphics object. The following is a quick C# example for using these properties. What it does is check to see what resolution the desktop is set at and retrieves an image at that resolution with a method called GetImage. And in the special case that the desktop is running some really strange dip setting we do the else case which takes the 120 dpi image and scales it appropriately.
System.Drawing.Bitmap bmp;
System.Drawing.Graphics g = this.CreateGraphics();

if ((g.DpiX = 96) && (g.DpiY = 96)) // this is now the defacto resolution for most systems
{
bmp = (Bitmap)GetImage("banner(96dpi)");
}
if ((g.DpiX = 72) && (g.DpiY = 72))
{
bmp = (Bitmap)GetImage("banner(72dpi)");
}
else if ((g.DpiX = 120) && (g.DpiY = 120))
{
bmp = (Bitmap)GetImage("banner(72dpi)");
}
else // this is where we take care of the really strange stuff
{
System.Drawing.Image img = GetImage("banner(120dpi)");
Size sz = new Size((int)(img.Width * (g.DpiX / img.HorizontalResolution)),
(int)(img.Width * (g.Dpiy / img.VerticalResolution)));
bmp = new Bitmap(img, sz);
}

So ends another adventure... except we need to apply this to all our forms that have image banners. Yay.

2 comments:

Unknown said...

dude,
I just ran into this on a WWII 'We can do it' image, and you've explained whats happening. Now I can fix it.
Thanks - you've saved me a bunch of time.

Motionless Mario said...

Glad to have been helpful! Just for curiosity's sake, what are you working on?

DF