天天看點

C# WinForm 列印

在工具箱中的列印工具中拖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);

        }

           

  這種方式的列印相當于頁面的截屏效果,如果列印時彈出的選擇列印機及相關設定的頁面在點選“列印”時未能及時關閉就會被抓到列印頁面中,是以為了避免這種情況,就把點選“列印”後的設定頁面拖動到需列印的頁面之外即可。

繼續閱讀