Daltons
Daltons

Reputation: 2711

Create BitmapSource from panel with Winform and WPF elements

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.

Upvotes: 1

Views: 384

Answers (1)

igorushi
igorushi

Reputation: 1995

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

Upvotes: 1

Related Questions