生成WPF窗口的屏幕截图

use*_*949 10 c# wpf

在winforms中,我们可以使用DrawToBitmap.在WPF中是否有类似的方法?

alm*_*ulo 11

你试过RenderTargetBitmap吗?https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap.aspx

这个使用有一些"截图"方法,就像这个从这里采取的:

    public static void CreateBitmapFromVisual(Visual target, string fileName)
    {
        if (target == null || string.IsNullOrEmpty(fileName))
        {
            return;
        }

        Rect bounds = VisualTreeHelper.GetDescendantBounds(target);

        RenderTargetBitmap renderTarget = new RenderTargetBitmap((Int32)bounds.Width, (Int32)bounds.Height, 96, 96, PixelFormats.Pbgra32);

        DrawingVisual visual = new DrawingVisual();

        using (DrawingContext context = visual.RenderOpen())
        {
            VisualBrush visualBrush = new VisualBrush(target);
            context.DrawRectangle(visualBrush, null, new Rect(new Point(), bounds.Size));
        }

        renderTarget.Render(visual);
        PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
        bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
        using (Stream stm = File.Create(fileName))
        {
            bitmapEncoder.Save(stm);
        }
    }
Run Code Online (Sandbox Code Playgroud)