Search code examples
.netwpfscreenshot

Save screenshot of WPF web browser Frame


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

With the help of the 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 web page as an image in my app?


Solution

  • Turns out the GDI Graphics class has a CopyFromScreen method that works well and captures the Frame's contents:

    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);