如何打印Windows窗体而不显示/显示它

我试图自动打印一系列Windows窗体。 我不需要展示它们。 我在互联网上找到的代码示例只有在我用show()显示Form时才有效! 我需要用数据初始化表单并将其发送到打印机这是我正在使用的代码:

 public partial class Form2_withoutShow : Form{ PrintDocument PrintDoc; Bitmap memImage; public Form2_withoutShow (Data data) { InitializeComponent(); /* Initialize Data (texboxes, charts ect.) here */ this.PrintDoc = new PrintDocument(); this.PrintDoc.PrintPage += PrintDoc_PrintPage; this.PrintDoc.DefaultPageSettings.Landscape = true; } public void Print() { this.PrintDoc.Print(); } void PrintDoc_PrintPage(object sender, PrintPageEventArgs e) { int x = SystemInformation.WorkingArea.X; int y = SystemInformation.WorkingArea.Y; int width = this.Width; int height = this.Height; Rectangle bounds = new Rectangle(x, y, width, height); Bitmap img = new Bitmap(width, height); this.DrawToBitmap(img, bounds); Point p = new Point(10, 10); e.Graphics.DrawImage(img, p); } private void Form2_withoutShow_Load(object sender, EventArgs e) { // remove TITLEBar this.ControlBox = false; this.Text = String.Empty; } } 

我从for循环中的另一个类调用Print()方法,并通过构造函数传递要初始化的Data。

MSDN 示例捕获屏幕上应显示表单的部分。 这对我不起作用。 如果我不调用show()我现在使用的方法现在只产生空窗口的打印。 如何在不调用show()方法的情况下将数据放入表单中? 在显示窗口时模仿窗口等方法也不起作用,因为这也是打印结果:最小化窗口。

在显示表单之前,表单及其控件未处于“已Created状态。 要强制创建表单及其控件,只需调用表单的内部CreateControl(bool fIgnoreVisible)方法:

 var f = new Form1(); var createControl = f.GetType().GetMethod("CreateControl", BindingFlags.Instance | BindingFlags.NonPublic); createControl.Invoke(f, new object[] { true }); var bm = new Bitmap(f.Width, f.Height); f.DrawToBitmap(bm, new Rectangle(0, 0, bm.Width, bm.Height)); bm.Save(@"d:\bm.bmp"); 

还要删除表单中的代码Load事件处理程序,并将它们放在表单的构造函数中。

注意

此问题还有其他解决方法:

  • 例如,您可以在屏幕边界之外的位置显示表单,然后再次隐藏它。 将Location设置为(-32000, -32000)并将StartPosition设置为Manual然后在绘制到位图之前ShowHide表单。
  • 或者作为另一个示例,您可以在将Opacity设置为0 Show表单,然后在绘制到位图之前ShowHide表单。