How to print a Windows Form without showing/displaying it

前端 未结 1 1971
执念已碎
执念已碎 2020-12-11 08:13

I am trying to print automatically a series of Windows-Forms. I don\'t need to show them. The code examples I found on the internet work only when I display the Form with

相关标签:
1条回答
  • 2020-12-11 08:41

    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.

    Note

    There are also other workarounds for the problem:

    • 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.
    0 讨论(0)
提交回复
热议问题