C# 有没有一种简单的方法可以打印出我的dotnetwindows表单?

C# 有没有一种简单的方法可以打印出我的dotnetwindows表单?,c#,winforms,printing,C#,Winforms,Printing,我刚刚创建了一个数据库应用程序来请求零件 它有几个表单,一个用于请求者,一个用于主管批准,一个用于采购批准,另一个用于职员知道要订购什么 现在我非常喜欢无纸化,但我的雇主真的很喜欢他们的论文。 有没有一种简单的方法可以将我的Windows窗体复制到纸上 我还应该补充一点,我仅限于使用2.0.Net框架 谢谢以下是一个可以满足您需求的解决方案: [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern

我刚刚创建了一个数据库应用程序来请求零件

它有几个表单,一个用于请求者,一个用于主管批准,一个用于采购批准,另一个用于职员知道要订购什么

现在我非常喜欢无纸化,但我的雇主真的很喜欢他们的论文。 有没有一种简单的方法可以将我的Windows窗体复制到纸上

我还应该补充一点,我仅限于使用2.0.Net框架

谢谢

以下是一个可以满足您需求的解决方案:

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern long BitBlt (IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
private 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);
   IntPtr dc1 = mygraphics.GetHdc();
   IntPtr dc2 = memoryGraphics.GetHdc();
   BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
   mygraphics.ReleaseHdc(dc1);
   memoryGraphics.ReleaseHdc(dc2);
}
private void printDocument1_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   e.Graphics.DrawImage(memoryImage, 0, 0);
}
private void printButton_Click(System.Object sender, System.EventArgs e)
{
   CaptureScreen();
   printDocument1.Print();
}

这里有一些注意事项-这里没有异常检查,而且您需要在完全信任的情况下运行才能使用非托管BitBlt API-但这可能是打印Windows窗体的最简单方法,只要它显示在屏幕上即可。

这里有一个快速方法。您可以清理代码以使其适合您的需要:

    public static class FormExtensions
    {
        public static void PrintForm(this Form f)
        {
            PrintDocument doc = new PrintDocument();
            doc.PrintPage += (o, e) =>
            {
                Bitmap image = new Bitmap(f.ClientRectangle.Width, f.ClientRectangle.Height);
                f.DrawToBitmap(image, f.ClientRectangle);

                e.Graphics.DrawImage(image, e.PageBounds);
            };

            doc.Print();
        }
    }
这会将表单拉伸到页面大小。如果需要,可以调整rhe DrawImage方法调用的第二个参数,以便在其他位置绘制它