如何使用c#在wpf中捕获WindowsFormsHost的图像

时间:2014-03-14 11:55:00

标签: c# wpf windowsformshost

我在WPF应用程序中有一个WindowsFormsHost面板,通过第三方dll绘制图形。我想捕获托管的面板。我尝试使用{RenderTargetBitmap},但它工作,只在面板后面保存网格。

我也尝试使用{DrawToBitmap}方法,如下所示,但它只给出空的白色区域。

path = @"E:\\whatever\\test.png";
var bmp = new System.Drawing.Bitmap((int)MyUserControl.myPanel.Width,(int)MyUserControl.myPanel.Height);
MyUserControl.myPanel.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);

请注意,此面板是在代码隐藏中添加的,而不是在xaml designer中添加。

我做错了什么或有其他解决方案吗?任何帮助。我可以找到类似的问题但不回答。

编辑:我也不想从屏幕上复制。如果可能的话,请告诉我?

1 个答案:

答案 0 :(得分:2)

喜欢这个吗?

需要引用System.Drawing和相应的用法:

using System.Drawing;
using System.Drawing.Imaging;

然后您可以在任何需要的地方添加:

        using (Bitmap newBmp = new Bitmap((int)Width, (int)Height, PixelFormat.Format24bppRgb))
        {
            System.Drawing.Point topLeftPoint = new System.Drawing.Point((int)Top, (int)Left);
            var graphics = Graphics.FromImage(newBmp);
            graphics.CopyFromScreen(topLeftPoint, System.Drawing.Point.Empty, new System.Drawing.Size((int)Width, (int)Height));
            newBmp.Save(@"c:\mypath\blah\", ImageFormat.Png);                
        }