2015-05-16 25 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 –

相關問題