1

I have a WPF panel (in a WPF application) that contains a collection of Winform and WPF elements. The Winform elements are hosted through a WindowsFormsHost.

I need to create a BitmapSource of the entire panel (exactly as it is), so I can manipulate it/save it/print it out.

It is not a problem to create a BitmapSource of the WPF elements but the Winform elements are not rendered (there is just a white space where they should be).

One example of that:

void GetBitmapSource(FrameworkElement element)
{
    var matrix = PresentationSource.FromVisual(element).CompositionTarget.TransformToDevice;
    double dpiX = 96.0 * matrix.M11;
    double dpiY = 96.0 * matrix.M22;
    var bitmapSource = new RenderTargetBitmap((int)element.ActualWidth + 1, (int)element.ActualHeight + 1, dpiX, dpiY, PixelFormats.Pbgra32);
    bitmapSource.Render(element);
    return bitmapSource;
}

This will print WPF elements just fine but ignore Winform content. How do I include that?

The image below shows a Tabpanel on the left and BitmapSource on the right. Notice how the content of the Winform Rectangle is empty. Tabpanel on the left and BitmapSource on the right.

Daltons
  • 2,671
  • 2
  • 18
  • 24

1 Answers1

1

How about taking a full screenshot and then cut it to element?

BitmapSource ScreenShot(int x, int y, int width, int height)
{
    using (var screenBitmap = new Bitmap(width,height,System.Drawing.Imaging.PixelFormat.Format32bppArgb))
    {
        using (var g = Graphics.FromImage(screenBitmap))
        {
            g.CopyFromScreen(x, y, 0, 0, screenBitmap.Size);
            var result = Imaging.CreateBitmapSourceFromHBitmap(
                screenBitmap.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            return result;
        }
    }
}
igorushi
  • 1,855
  • 21
  • 19
  • This is so dirty it should be in a spoiler box with a big "NSFW" warning at the top ... but **it works**! (I have to print a template WPF control that has a Windows Forms Hosted control somewhere in its visual tree and this is the only thing I've found that doesn't leave a black or white rectangle. Regrettably, the output quality is poor, but beggars can't be choosers.) – Evil Dog Pie Mar 28 '17 at 15:39