简体   繁体   中英

Print form in Windows application

Im trying to get a button to print out my current form and have tried all the code I can find on here but it keeps printing blank pages and I cant work out why.

The code I use is as follows

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);
}

This runs from a button (btnPrint) which is on a form (Form2) along with loads of textboxes and graphics)

When clicked it brings up the print preview dialog fine but the page is blank. If I press print it prints a blank page.

Any idea why its not copying the form??

Please refer: 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM