更新:2007 年 11 月
這個範例示範列印預覽目前的表單。
範例
[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.Show();
}
編譯程式碼
這個範例需要:
名為 printDocument1 且具有 PrintPage 事件處理常式的 PrintDocument 元件。
名為 printPreviewDialog1,且其文件屬性設定為 printDocument1 的 PrintPreviewDialog。
名為 printButton 且具有 Click 事件處理常式的 Button。
範例程式碼會取代現有的事件處理常式。在按下 printButton 時,會顯示表單的列印預覽。
穩固程式設計
以下情形可能會導致例外狀況:
您沒有印表機的存取權限。
您沒有 Unmanaged 程式碼的使用權限。
未安裝任何印表機。
先前已處置預覽列印對話方塊。在預覽列印對話方塊關閉後,會發生這種情況。
安全性
您必須具有執行 Unmanaged 程式碼和存取印表機的權限,才能執行這個範例。