Using RenderTargetBitmap on WindowsFormsHost

前端 未结 2 1307
天命终不由人
天命终不由人 2021-01-06 08:47

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

相关标签:
2条回答
  • 2021-01-06 09:14

    A Windows Forms control also knows how to render itself, you don't have to jump through the screen capture hoop. Make it look like this:

        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");
        }
    
    0 讨论(0)
  • 2021-01-06 09:27

    The content of the WindowsFormsHost is rendered by GDI+, like in a Windows Forms application, so you can't use RenderTargetBitmap for that since it is not rendered by WPF. Instead, you should use the GDI+ BitBlt function, which allows you to make a capture of an area on the screen.

    See this post for an example


    UPDATE: here's another version of the code, updated for use with 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;
    }
    

    Just call pass your WindowsFormsHost control as a parameter to the Capture method, and do whatever you like with the resulting ImageSource. For the definitions of BitBlt and GetDC, have a look at this website (I wrote that on my home computer, which I can't access from where I am now)

    0 讨论(0)
提交回复
热议问题