且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-06 12:37:58

显示窗体之前,窗体和控件不在的 创建 状态。要强制窗体和控件要创建它足以调用内部的 CreateControl(布尔fIgnoreVisible) 窗体的方法:

Before showing the form, the form and its controls are not in Created state. To force the form and its controls to be created it's enough to call internal CreateControl(bool fIgnoreVisible) method of your form:

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



同时删除您的表单中有代码加载事件处理程序,并把它们在窗体的构造函数。

Also remove codes which you have in your form Load event handler, and put them in constructor of your form.

注意

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

There are also other workarounds for the problem:


  • 例如,您可以显示表单中的位置在屏幕的边界之外和然后再次将其隐藏。在位置设置为( - 32000,-32000)并设置中StartPosition 手动然后显示隐藏的形式绘制位图前。

  • 或作为另一个例子,可以显示与透明度设置为的形式0 然后显示隐藏绘制位图前的形式。

  • For example you can show the form in a location outside of boundary of the screen and then hide it again. Set the Location to (-32000, -32000) and set StartPosition to be Manual then Show and Hide the form before drawing to bitmap.
  • Or as another example, you can show the form with Opacity set to 0 and then Show and Hide the form before drawing to bitmap.