C# 拍摄动态打开的windows窗体c的屏幕截图#

C# 拍摄动态打开的windows窗体c的屏幕截图#,c#,winforms,bitmap,C#,Winforms,Bitmap,我在变量中有表单的名称,我需要显示该表单,截图,并将其转换为字节,以便将其保存在数据库中 我的代码是这样的: var form = (Form)Activator.CreateInstance(Type.GetType(string.Format("namespace.{0}", FormName)), Parameter1, Parameter2); using (var bitmap = new Bitmap(form.Width, form.Height - 50)) { f

我在变量中有表单的名称,我需要显示该表单,截图,并将其转换为字节,以便将其保存在数据库中

我的代码是这样的:

 var form = (Form)Activator.CreateInstance(Type.GetType(string.Format("namespace.{0}", FormName)), Parameter1, Parameter2);
 using (var bitmap = new Bitmap(form.Width, form.Height - 50))
 {
    form.Show();
    DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));

    byte[] bytes;
    using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
    {
       bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
       bytes = stream.ToArray();
    }
    form.Close();
 }
问题是,我从主窗体得到截图,而不是我想要的子窗体。。。有什么办法可以做到这一点吗


也许这段代码应该在子表单中,但我不知道如何从动态from动态调用方法。

您可以友好地处理要截图的表单的
FormClosed
事件。您需要特别注意
边界

 Form f = new Form();
            f.FormClosed += (se, ev) => {
                Rectangle bounds = f.Bounds; //Important to set the bounds of the Form you want to screenshot
                using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
                {
                    using (Graphics graph = Graphics.FromImage(bitmap))
                    {
                        graph.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
                    }
                    bitmap.Save("screenshot.png", ImageFormat.Png);
                }
            };
            f.Show();
            System.Threading.Thread.Sleep(2000);

            f.Close();

在这种情况下,我必须等待
2000毫秒
。给要画的形状足够的时间。但是,您可以处理其他事件。i、 e.点击表单中的
按钮

只是忘记了
表单。
DrawToBitmap中
我实际上通过添加“form.DrawToBitmap…”而不是“DrawToBitmap”解决了这个问题。这是一个表单方法,它从被调用的表单中获取数据。