在后台线程中创建 WPF 控件的屏幕截图



我们需要在后台线程中创建WPF控件(例如,带有一些图像的画布),然后截取它们的屏幕截图。不得显示控件。

我设法通过使其成为 STA 线程在线程上创建控件。然后我使用此处的代码 http://blogs.msdn.com/b/swick/archive/2007/12/02/rendering-ink-and-image-to-a-bitmap-using-wpf.aspx 创建屏幕截图。

但这不起作用:控件的大小始终为 0,因此会崩溃。即使我手动指定宽度和高度,它也不起作用,保存的图像始终是黑色的。

这是我的代码:

private void CreateScreenshotThread()
{
    var image = CreateImage();
    TakeScreenshot(image , @"e:1.bmp");
}

我也尝试了UpdateLayout(),但没有成功。您知道如何强制执行控件的布局更新和呈现吗?我玩过PresentationSource,但没有成功(不完全理解该类的目的)。

有可能,您缺少的位可能是控件的度量和排列:

    public MainWindow()
    {
        InitializeComponent();
        var thread = new Thread(CreateScreenshot);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }
    private void CreateScreenshot()
    {
        Canvas c = new Canvas { Width = 100, Height = 100 };
        c.Children.Add(new Rectangle { Height = 100, Width = 100, Fill = new SolidColorBrush(Colors.Red) });
        var bitmap = new RenderTargetBitmap((int)c.Width, (int)c.Height, 120, 120, PixelFormats.Default);
        c.Measure(new Size((int)c.Width, (int)c.Height));
        c.Arrange(new Rect(new Size((int)c.ActualWidth, (int)c.ActualHeight)));
        bitmap.Render(c);
        var png = new PngBitmapEncoder();
        png.Frames.Add(BitmapFrame.Create(bitmap));
        using (Stream stm = File.Create("c:\temp\test.png"))
        {
            png.Save(stm);
        }
    }

最新更新