DPI-aware NetCF v1 apps

.NetCF 2.0 has great support for hi-dpi devices, but v1 does not have anything built in. Luckily, it's not that hard to add hi-dpi support to Forms-based apps. Just add a call to DpiHelper.AdjustAllControls(this); to the end of your form's constructor. And if you do any manual drawing, you can use DpiHelper.Scale() to convert hard-coded pixel constants from 96dpi to the dpi of the device.

/// <summary>A helper object to adjust the sizes of controls based on the DPI.</summary>
public class DpiHelper
{
/// <summary>The real dpi of the device.</summary>
private static int dpi = SafeNativeMethods.GetDeviceCaps(IntPtr.Zero, /*LOGPIXELSX*/88);

        /// <summary>Adjust the sizes of controls to account for the DPI of the device.</summary>
/// <param name="parent">The parent node of the tree of controls to adjust.</param>
public static void AdjustAllControls(Control parent)
{
if (dpi == 96)
return;
foreach (Control child in parent.Controls)
{
AdjustControl(child);
AdjustAllControls(child);
}
}

        public static void AdjustControl(Control control)
{
control.Bounds = new Rectangle(
control.Left * dpi / 96,
control.Top * dpi / 96,
control.Width * dpi / 96,
control.Height * dpi / 96 );
}

        /// <summary>Scale a coordinate to account for the dpi.</summary>
/// <param name="x">The number of pixels at 96dpi.</param>
public static int Scale(int x)
{
return x * dpi / 96;
}

        private class SafeNativeMethods
{
[DllImport("coredll.dll")]
static internal extern int GetDeviceCaps(IntPtr hdc, int nIndex);
}
}

- Jason Fuller

Comments

  • Anonymous
    December 28, 2005
    well the code above will have no affect on scaling.. you have to use double or float in the data type :-)

    as ( dpi / 96) will always result in 1 ... even if the dpi = 131 131/96 will be integer division and resut willbe 1 ...

  • Anonymous
    January 05, 2006
    The code works. There is a difference between (dpi / 96) and x * dpi / 96.
  • Anonymous
    August 09, 2006
    Does my app needs to be recompiled with res2exe? Without using it I'm always getting 96 dpi on my device (dell x51v). But using it I have to resize all forms manually.
    BTW, I need just detection of screen resolution - VGA, qVGA or square..
  • Anonymous
    August 09, 2006
    Does my app needs to be recompiled with res2exe? Without using it I'm always getting 96 dpi on my device (dell x51v). But using it I have to resize all forms manually.
    BTW, I need just detection of screen resolution - VGA, qVGA or square..
  • Anonymous
    August 15, 2008
    > There is a difference between (dpi / 96) and x * dpi / 96. even though * has precedence on /, it's a good idea to use parenthesis in this case.