在工具箱中的打印工具中拖printDialog、printDocument、printPreviewDialog、pageSetupDialog到页面中。页面中拖三个按钮,分别是“打印”、“打印设置”、“打印预览”。
代码如下:
//打印
private void btnPrint_Click(object sender, EventArgs e)
{
if (this.printDialog1.ShowDialog() == DialogResult.OK)
CaptureScreen();
this.printDocument1.Print();
}
//打印预览
private void btnView_Click(object sender, EventArgs e)
{
CaptureScreen();
this.printPreviewDialog1.ShowDialog();
}
//打印设置
private void btnSet_Click(object sender, EventArgs e)
{
this.pageSetupDialog1.ShowDialog();
}
//如果要打印整个窗体
[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 void CaptureScreen()
{
Graphics mygraphics = this.panel1 .CreateGraphics ();
Size s = this.panel1 .Size; //如果要打印整个窗体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.Width, this.Height, dc1, 0, 0, 13369376);
mygraphics.ReleaseHdc(dc1);
memoryGraphics.ReleaseHdc(dc2);
}
这种方式的打印相当于页面的截屏效果,如果打印时弹出的选择打印机及相关设置的页面在点击“打印”时未能及时关闭就会被抓到打印页面中,所以为了避免这种情况,就把点击“打印”后的设置页面拖动到需打印的页面之外即可。