Save screenshot of WPF web browser.

I have an element Framedisplaying an html page in my WPF application and would like to save a screenshot of the frame as an image.

Using google, I have this code:

Size size = new Size(PreviewFrame.ActualWidth, PreviewFrame.ActualHeight);
PreviewFrame.Measure(size);
PreviewFrame.Arrange(new Rect(size));

var renderBitmap = new RenderTargetBitmap(
            (int)size.Width,
            (int)size.Height,
            96d,
            96d,
            PixelFormats.Pbgra32);
renderBitmap.Render(PreviewFrame);

But all I ever get is a blank image.

Any thoughts on how to fix this code and / or another way to capture a webpage as an image in my application?

+3
source share
1 answer

It turns out that the GDI class Graphicshas a method CopyFromScreenthat works well and captures content Frame:

var topLeftCorner = PreviewFrame.PointToScreen(new System.Windows.Point(0, 0));
var topLeftGdiPoint = new System.Drawing.Point((int)topLeftCorner.X, (int)topLeftCorner.Y);
var size = new System.Drawing.Size((int)PreviewFrame.ActualWidth, (int)PreviewFrame.ActualHeight);

var screenShot = new Bitmap((int)PreviewFrame.ActualWidth, (int)PreviewFrame.ActualHeight);

using (var graphics = Graphics.FromImage(screenShot)) {
    graphics.CopyFromScreen(topLeftGdiPoint, new System.Drawing.Point(),
        size, CopyPixelOperation.SourceCopy);
}

screenShot.Save(@"C:\screenshot.png", ImageFormat.Png);
+2
source

Source: https://habr.com/ru/post/1768489/


All Articles