wpfscreencapturerendertargetbitmap

Has a unexpected transparent area in image that RenderTargetBitmap captured wpf control


I tried to capture main window wpf application to png image by RenderTargetBitmap class. It work well except the image has a small transparent area at the bottom and the left. This is code and captured image:

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        string folder = "screenshot";
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }

        string filename = "ScreenCapture_" + DateTime.Now.ToString("ddMM_hhmmss") + ".png";

        string filePath = folder + "//" + filename;

        RenderTargetBitmap renderTargetBitmap =
            new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Pbgra32);
            renderTargetBitmap.Render(this);
            PngBitmapEncoder pngImage = new PngBitmapEncoder();
            pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
            using (Stream fileStream = File.Create(filePath))
            {
                pngImage.Save(fileStream);
            }
    }

Captured image has transparent part at bottom


Solution

  • A Window's ActualWidth and ActualHeight includes the size of the border and title bar.

    Instead of the Window, you should render its top level child element, i.e. its Content:

    var contentElement = (FrameworkElement)Content;
    
    var renderTargetBitmap = new RenderTargetBitmap(
        (int)contentElement.ActualWidth, (int)contentElement.ActualHeight,
        96, 96, PixelFormats.Default);
    
    renderTargetBitmap.Render(contentElement);