在Windows应用程序中打印表单

时间:2015-05-16 16:37:15

标签: c# winforms printing desktop-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)以及大量文本框和图形开始的。

单击时会打开打印预览对话框,但页面为空白。如果我按下打印它会打印一个空白页。

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

1 个答案:

答案 0 :(得分:2)

请参阅: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();
}