这应该很简单。我基本上复制了MSDN中的代码,用于在我的C#winforms应用程序中打印表单。我点击“打印”时得到的只是一张白纸,但没有错误信息。
这是链接。 https://msdn.microsoft.com/en-us/library/aa287529%28v=vs.71%29.aspx
代码是:
[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();
printDocument1.Print();
}
我需要做的就是打印当前表格。我刚拿到一张白纸。我认为这是因为非托管代码(调用dll)。我该如何解决这个问题?
答案 0 :(得分:3)
我在.NET 4.5.2中测试过该样本,效果很好。
我刚拿到一张白纸。我认为这是因为非托管代码(调用dll)。我该如何解决这个问题?
如果您没有为PrintDocument.PrintPage
事件挂断订阅者,您将收到一张白纸。
private void printDocument1_PrintPage(Object sender, PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage, 0, 0);
}
答案 1 :(得分:2)
您链接的页面是2003年,可能不再有效了。
以下是最新的MSDN页面:How to: Print a Windows Form
您只需要访问打印机的权限。
完整代码:
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
public class Form1 :
Form
{
private Button printButton = new Button();
private PrintDocument printDocument1 = new PrintDocument();
public Form1()
{
printButton.Text = "Print Form";
printButton.Click += new EventHandler(printButton_Click);
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
this.Controls.Add(printButton);
}
void printButton_Click(object sender, EventArgs e)
{
CaptureScreen();
printDocument1.Print();
}
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);
memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
}
private void printDocument1_PrintPage(System.Object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage, 0, 0);
}
public static void Main()
{
Application.Run(new Form1());
}
}