0

I have this function, which is called from a button Click event handler:

private void CreateFrame(Page page)
{
    Frame newFrame = new Frame();
    newFrame.Navigate(page);

    // FramesHolder is a StackPanel with multiple Frames inside it
    FramesHolder.Children.Add(newFrame);

    // The size the page is 525x50
    RenderTargetBitmap renderTargetBitmap =
        new RenderTargetBitmap(525, 50, 96, 96, PixelFormats.Pbgra32);
    renderTargetBitmap.Render(newFrame);
    PngBitmapEncoder pngImage = new PngBitmapEncoder(); 

    pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
    using (Stream fileStream = File.Create("Frame.png"))
    {
        pngImage.Save(fileStream);
    }
}

The problem is that the Frame.png image is rendered black. How to fix it? Thanks.

Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • http://stackoverflow.com/questions/24466482/how-to-take-a-screenshot-of-a-wpf-control – CathalMF Apr 14 '16 at 15:42
  • Well - that is actually the original answer I get this code from, but in that scenario, the control is created in the XAML while mine is created only when the button is clicked, which I believe is the difference that make the picture black. – Michael Haddad Apr 14 '16 at 15:47
  • At what time are you executing the method? Maybe it is taking the screenshot before the control is fully drawn? – CathalMF Apr 14 '16 at 15:49
  • @CathalMF - When a button is clicked. And, well, In this code the `newFrame` is drawn before The `RenderTargetBitmap` object is created... In a previous question I ask this in a comment and someone suggested that it has to do with the `Measure` and `Arrange` methods but I cannot figure it out... Thanks... – Michael Haddad Apr 14 '16 at 15:53

1 Answers1

1

I changed the renderTargetBitmap.Render(newFrame); line to renderTargetBitmap.Render(page); and it successfully takes the screenshot.

The problem is in the creation of your new frame.

I displayed a page and in the Loaded event i called your method with the change i specified above and it works.

public partial class Page2 : System.Windows.Controls.Page
{
    public Page2()
    {
        InitializeComponent();
    }

    private void PG2_Loaded(object sender, RoutedEventArgs e)
    {
        CreateFrame(this);
    }

    private void CreateFrame(Page page)
    {
        Frame newFrame = new Frame();
        newFrame.Navigate(page);

        // The size the page is 525x50
        RenderTargetBitmap renderTargetBitmap =
            new RenderTargetBitmap(525, 50, 96, 96, PixelFormats.Pbgra32);
        renderTargetBitmap.Render(page);
        PngBitmapEncoder pngImage = new PngBitmapEncoder();

        pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
        using (Stream fileStream = File.Create("c:\\Frame.png"))
        {
            pngImage.Save(fileStream);

        }
    }

}
CathalMF
  • 9,705
  • 6
  • 70
  • 106