Tuesday 1 May 2012

Print Content of Panel in winform


private void btnPrint_Click(object sender, EventArgs e)
        {
         Pd.PrintPage += PrintPage;
         Pd.DefaultPageSettings.PaperSize = new PaperSize("Custom",
                                                           panel1.Width+20,
                                                           panel1.Height+15 );
         Pd.Print();
        }
[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(Panel pnl)
        {
            Graphics mygraphics = pnl.CreateGraphics();
            Size s = pnl.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, pnl.Width, pnl.Height, dc1, 0, 0, 13369376);
            mygraphics.ReleaseHdc(dc1);
            memoryGraphics.ReleaseHdc(dc2);
        }
private void PrintPage(System.Object sender,
                       System.Drawing.Printing.PrintPageEventArgs e)
        {
            CaptureScreen(panel1);
            e.Graphics.DrawImage(memoryImage, 5, 5);
        }

2 comments:

  1. Thanks, but print/image quality gets dull in this case. pls suggest if you have any better idea

    ReplyDelete