如何截取WPF控件的截图?

我使用Bing地图WPF控件创build了一个WPF应用程序。 我想只能截图Bing地图控件。

使用这个代码来制作屏幕截图:

// Store the size of the map control int Width = (int)MyMap.RenderSize.Width; int Height = (int)MyMap.RenderSize.Height; System.Windows.Point relativePoint = MyMap.TransformToAncestor(Application.Current.MainWindow).Transform(new System.Windows.Point(0, 0)); int X = (int)relativePoint.X; int Y = (int)relativePoint.Y; Bitmap Screenshot = new Bitmap(Width, Height); Graphics G = Graphics.FromImage(Screenshot); // snip wanted area G.CopyFromScreen(X, Y, 0, 0, new System.Drawing.Size(Width, Height), CopyPixelOperation.SourceCopy); string fileName = "C:\\myCapture.bmp"; System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.OpenOrCreate); Screenshot.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp); fs.Close(); 

我的问题:

WidthHeight似乎不好(错误值)。 生成的屏幕截图似乎使用错误的坐标。

我的截图:

我的截图

我期望的是:

期望的屏幕截图

为什么我会得到这个结果? 我尝试在发布模式,没有Visual Studio,结果是一样的。

屏幕截图是屏幕上的一切 …屏幕上的所有内容 。 你想要的是从一个单一的UIElement保存图像,你可以使用RenderTargetBitmap.Render方法 。 这个方法需要一个Visualinput参数,幸运的是,这是所有UIElement的基类之一。 所以假设你想保存一个.png文件,你可以这样做:

 RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); renderTargetBitmap.Render(yourMapControl); PngBitmapEncoder pngImage = new PngBitmapEncoder(); pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); using (Stream fileStream = File.Create(filePath)) { pngImage.Save(fileStream); }