Using RenderTargetBitmap in WindowsFormsHost

I have a set of controls inside WindowsFormsHost, and I would like to capture the current view and just save it as an image, however I only get the image Panelvisible in the image.

Is it possible to use WindowsFormsHost as "Visual" and grab wrapped controls?

See my example:

<WindowsFormsHost x:Name="windowHost">
    <wf:Panel Dock="Fill" x:Name="basePanel"/>
</WindowsFormsHost>

If I were to add a button or something in basePanel, it would not be visible when exporting to PNG with the following code:

 RenderTargetBitmap rtb = new RenderTargetBitmap(basePanel.Width, 
                                 basePanel.Height, 96, 96, PixelFormats.Pbgra32);
 rtb.Render(windowHost);

 PngBitmapEncoder pnge = new PngBitmapEncoder();
 pnge.Frames.Add(BitmapFrame.Create(rtb));
 Stream stream = File.Create("test.jpg");

 pnge.Save(stream);

 stream.Close();

Suggestions about why this might not work, or maybe a workaround? I think this is actually not the case, but hopefully!

+3
source share
2

Windows Forms , . :

    using (var bmp = new System.Drawing.Bitmap(basePanel.Width, basePanel.Height)) {
        basePanel.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height));
        bmp.Save(@"c:\temp\test.png");
    }
+4

WindowsFormsHost GDI +, Windows Forms, RenderTargetBitmap , WPF. GDI + BitBlt, .

.


UPDATE: , WPF:

using System.Drawing;
...

public static ImageSource Capture(IWin32Window w)
{
    IntPtr hwnd = new WindowInteropHelper(w).Handle;
    IntPtr hDC = GetDC(hwnd);
    if (hDC != IntPtr.Zero)
    {
        Rectangle rect = GetWindowRectangle(hwnd);
        Bitmap bmp = new Bitmap(rect.Width, rect.Height);
        using (Graphics destGraphics = Graphics.FromImage(bmp))
        {
            BitBlt(
                destGraphics.GetHdc(),
                0,
                0,
                rect.Width,
                rect.Height,
                hDC,
                0,
                0,
                TernaryRasterOperations.SRCCOPY);
        }
        ImageSource img = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            bmp.GetHBitmap(),
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
        return img;
    }
    return null;
}

WindowsFormsHost Capture , , ImageSource. BitBlt GetDC - ( , 't , )

+6

Source: https://habr.com/ru/post/1723236/


All Articles