当DPI为150%时,我的表单无法正确打印

时间:2016-03-29 20:47:37

标签: c# winforms scale

我有一个可以在我的机器上正确打印的表单,但是当我在另一台机器上部署该应用程序时,该表单不适合页面,并且打印文档上会出现桌面背景。两台机器之间的主要区别在于其中一台DPI设置为150%。我已多次更改自动缩放但没有任何变化。表单在屏幕上看起来不错,但是打印不正确。以下是我正在使用的代码。

private void btnPrint_Click(object sender, EventArgs e)
    {
        CaptureScreen();
        printPreviewDialog1.Document = printDocument1;
        printPreviewDialog1.ShowDialog();            
    }

    Bitmap memoryImage;

    private void CaptureScreen()
    {
        Graphics myGraphics = this.CreateGraphics();
        Size s = this.Size;
        memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
        Graphics memoryGraphics = Graphics.FromImage(memoryImage);
        memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
    }

    private void printDocument1_PrintPage(System.Object sender,
           System.Drawing.Printing.PrintPageEventArgs e)
    {            
        e.Graphics.DrawImage(memoryImage, 0, 0);
    }

1 个答案:

答案 0 :(得分:4)

通过增加Windows字体大小并让应用程序处理扩展,但通过让操作系统为您进行扩展,可以获得较高的dpi缩放(如旧的125%缩放)。在这种模式下,操作系统依赖于应用程序的实际dpi设置,并在绘制表面时自行缩放应用程序。

结果是在应用程序内部,像素位置和大小不是屏幕上使用的实际像素位置和大小。但CopyFromScreen()方法需要实际的像素坐标和大小。您需要找出应用程序经历的像素缩放,然后将此缩放应用于您使用的坐标。

以下是工作代码(getScalingFactor()方法从this answer被盗)。

[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
public enum DeviceCap
{
    VERTRES = 10,
    DESKTOPVERTRES = 117,
}

private float getScalingFactor()
{
    using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
    {
        IntPtr desktop = g.GetHdc();
        try
        {
            int LogicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES);
            int PhysicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES);
            float ScreenScalingFactor = (float)PhysicalScreenHeight / (float)LogicalScreenHeight;
            return ScreenScalingFactor; 
        }
        finally
        {
            g.ReleaseHdc();
        }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    using (Graphics myGraphics = this.CreateGraphics())
    {
        var factor = getScalingFactor();
        Size s = new Size((int)(this.Size.Width * factor), (int)(this.Size.Height * factor));

        using (Bitmap memoryImage = new Bitmap(s.Width, s.Height, myGraphics))
        {
            using (Graphics memoryGraphics = Graphics.FromImage(memoryImage))
            {
                memoryGraphics.CopyFromScreen((int)(Location.X * factor), (int)(Location.Y * factor), 0, 0, s);
                memoryImage.Save(@"D:\x.png", ImageFormat.Png);
            }
        }
    }
}