C# 位图活动窗体 > 对象引用未设置为对象的实例

C# Bitmap Active Form > Object reference not set to an instance to an object

几天来我一直在尝试解决活动表单的屏幕截图功能中的错误...

Object reference not set to an instance to an object

我的问题:运行 我的 exe 几个小时后,出现错误(重新开始,它没有错误)

函数的作用:打开表格、初始化新图表、填写表格、截图表格并保存截图...

代码>

                var frm = Form3.ActiveForm;
                await Task.Delay(2000);
                using (var bmp = new Bitmap(frm.Width, frm.Height))
                {
                    frm.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
                    bmp.Save("TestX.png");
                }

其他代码,但无法解决错误

        WindowState = FormWindowState.Maximized;
        FormBorderStyle = FormBorderStyle.None;
        Bounds = Screen.PrimaryScreen.Bounds;
        BringToFront();

错误在这里 > ... (frm.Width, frm.Height) 因为表单不在我所有其他应用程序的前面并且没有 Width/Hight 我想...如果我重新启动 exe,错误就解决了,我的表单再次出现在所有其他应用程序的前面,然后几个小时后我又遇到了问题...

有什么技巧可以解决吗it/or表格一定不能放在最前面?

这是因为,在某些时候,您的应用程序不再具有活动表单,并且 Form3.ActiveForm 属性 returns null 而不是表单对象。参见 the documentation

我建议您不要使用 .ActiveForm 而是做一些其他事情来确定当前表单(我怀疑它是否必须处于活动状态)- 如果此代码是您表单代码隐藏的一部分,那么甚至 this 会起作用

using (var bmp = new Bitmap(this.Width, this.Height))

如果代码不在您的表单代码隐藏中,您可以将您的表单实例传递给任何助手 class 正在创建屏幕截图

ScreenshotHelper sh = new ScreenshotHelper(this); // assuming you create the helper as part of your form codebehind