如何获取WPF控件的屏幕截图?

Wal*_*oni 27 .net c# wpf system.drawing screenshot

我使用Bing地图WPF控件创建了一个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();
Run Code Online (Sandbox Code Playgroud)

我的问题:

WidthHeight似乎是坏的(假值).生成的屏幕截图似乎使用了不良坐标.

我的截图:

我的截图

我期待的是:

所需的截图

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

She*_*dan 49

屏幕截图是屏幕的一个镜头...... 屏幕上的所有内容.你想要的是从一个单独保存图像UIElement,你可以使用RenderTargetBitmap.Render方法.这个方法接受一个Visual输入参数,幸运的是,这是所有UIElements 的基类之一.因此,假设您要保存.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);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我想在`image`控件中显示这个`pngImage`而不是保存`pngImage`怎么办 (2认同)
  • 值得一提的是,`PixelFormats.Pbgra32` 是这里唯一支持的格式。您可以更隐式地将其指定为`PixelFormats.Default`。 (2认同)