I\'m working on a migration project in which a database actually stores display sizes in twips. Since I can\'t use twips to assign sizes to WPF or Winforms controls, I was w
For reference, another C# version, using the Win32 API instead of requiring a Graphics
objects:
using System.Runtime.InteropServices;
static class SomeUtils {
public static int ConvertTwipsToPixels(int twips, MeasureDirection direction) {
return (int)(((double)twips)*((double)GetPixperinch(direction))/1440.0);
}
public static int ConvertPixelsToTwips(int pixels, MeasureDirection direction) {
return (int)((((double)pixels)*1440.0)/((double)GetPixperinch(direction)));
}
public static int GetPPI(MeasureDirection direction) {
int ppi;
IntPtr dc = GetDC(IntPtr.Zero);
if (direction == MeasureDirection.Horizontal)
ppi = GetDeviceCaps(dc, 88); //DEVICECAP LOGPIXELSX
else
ppi = GetDeviceCaps(dc, 90); //DEVICECAP LOGPIXELSY
ReleaseDC(IntPtr.Zero, dc);
return ppi;
}
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int devCap);
}
public enum MeasureDirection {
Horizontal,
Vertical
}
The MeasureDirection
is supposed to be specified as there is no guarantee that pixels are always square (according to the kb).
Reference: kb210590: ACC2000: How to Convert Twips to Pixels