使用WPF捕获给定窗口

时间:2013-09-11 14:29:58

标签: c# wpf

有人能为我提供在WPF应用程序中捕获给定窗口的代码吗? 我已经在Windows窗体应用程序中实现了它,但它在WPF中变得混乱。

1 个答案:

答案 0 :(得分:1)

如果您想要保存窗口的图像,可以创建一个RenderTargetBitmap对象并将窗口渲染到它。

/// <summary>
/// Captures a controls visual and saves it to the file system.
/// </summary>
/// <param name="visual">A reference to the <see cref="Visual"/> that you want to capture.</param>
/// <param name="fileName">The file name that you want the image saved as.</param>
void CaptureImage(Visual visual, string fileName)
{
    if (File.Exists(fileName))
        File.Delete(fileName);

    using (FileStream fileStream = new FileStream(fileName, FileMode.CreateNew))
    {
        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)Width, (int)Height, 96, 96, PixelFormats.Pbgra32);
        renderTargetBitmap.Render(this);
        var encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
        encoder.Save(fileStream);
    }
}

与线一起使用。

CaptureImage(this, @"c:\temp\screencap.png");