2015-05-16 24 views
0

我试图获得一个按钮来打印出我当前的表单,并尝试了所有我可以在这里找到的代码,但它仍然打印空白页,我无法解决原因。在Windows应用程序中打印表格

我使用的代码如下

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); 
} 

这从按钮(btnPrint),它是一个窗体(Form 2)上运行,以文本框的负荷和图形)

沿着当点击它带来打印预览对话框正常,但页面为空白。如果我按打印它打印一个空白页。

任何想法为什么它不复制的形式?

+0

您可以通过与面板搞乱砍死这个代码死亡。您的printDocument1.PrintPage事件处理程序的事件处理程序看起来很糟糕。使用调试器,在PrintPage事件处理程序上设置断点。预测它不会中断。双击设计器中的printDocument1组件以添加事件处理程序。 –

+0

或更好的是:扔掉它,写一个体面的打印例程,而不是倾倒屏幕分辨率到您的打印机.. – TaW

+0

对不起,我对此很新,我只是直接从这里的文章使用此代码,只是couldn' t看看它不在工作 –

回答

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(); 
} 
+0

我在使用这段代码之前它运行,但当打印预览窗口出现它说“文档不包含任何页面”不知道我要去哪里错了 –

+0

你能分享你的代码在驱动器或什么? –

+0

https://www.dropbox.com/s/vubnjiq9uyopfio/code.txt?dl=0 –

相关问题