在 Windows 应用程序中打印表格

Print form in Windows application

我正在尝试获取一个按钮来打印我当前的表单,并尝试了我可以在此处找到的所有代码,但它一直在打印空白页,我无法弄清楚原因。

我使用的代码如下

Bitmap bitmap;
private void btnPrint_Click(object sender, EventArgs e)
{
//Add a Panel control.
Panel panel = new Panel();
this.Controls.Add(panel);

//Create a Bitmap of size same as that of the Form.
Graphics grp = panel.CreateGraphics();
Size formSize = this.ClientSize;
bitmap = new Bitmap(formSize.Width, formSize.Height, grp);
grp = Graphics.FromImage(bitmap);

//Copy screen area that that the Panel covers.
Point panelLocation = PointToScreen(panel.Location);
grp.CopyFromScreen(panelLocation.X, panelLocation.Y, 0, 0, formSize);

//Show the Print Preview Dialog.
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.PrintPreviewControl.Zoom = 1;
printPreviewDialog1.ShowDialog();
}

private void PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//Print the contents.
e.Graphics.DrawImage(bitmap, 0, 0);
}

这从表单 (Form2) 上的按钮 (btnPrint) 以及大量文本框和图形)运行

点击后会弹出打印预览对话框,但页面是空白的。如果我按打印,它会打印一张空白页。

知道为什么它不复制表格吗??

请参考:How to: Print Preview a Form

[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();
    printPreviewDialog1.Document = printDocument1;
    printPreviewDialog1.Show();
}