C#根据显示器分辨率进行毫米与像素的单位换算
作者:C/S框架网|www.cscode.ne  发布日期:2019/10/23 13:57:20
  C#根据显示器分辨率进行毫米与像素的单位换算

在.NET开发环境下Winform界面的组件以像素作为尺寸单位的,像素是显示器分辨率的尺寸单位,在进行项目开发中,如开发报表,有时需要进行毫米转换为像素。因为转换与当前显示器分辨率有关,在不同分辨率下转换的系数不同,下面是借助GDI绘图机制进行毫米转换像素。


C# Code:


public static double MillimetersToPixelsWidth(double length) //length是毫米,1厘米=10毫米
{
   System.Windows.Forms.Panel p = new System.Windows.Forms.Panel();
   System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle);
   IntPtr hdc = g.GetHdc();
   int width = GetDeviceCaps(hdc, 4); // HORZRES
   int pixels = GetDeviceCaps(hdc, 8); // BITSPIXEL
   g.ReleaseHdc(hdc);
   return (((double)pixels / (double)width) * (double)length);
}

[DllImport("gdi32.dll")]
private static extern int GetDeviceCaps(IntPtr hdc, int Index);

//来源:C/S框架网(www.csframework.com) QQ:23404761



上一篇 下一篇