最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Is there a way to capture a bitmap view of a WPF window which is never shown? - Stack Overflow

programmeradmin6浏览0评论

For example I have a WPF window:

public class MyWindow : Window
{
    public MyWindow()
    {
        InitializeStyle();
        InitializeContent();
        InitializeSizePosition();
    }

    // ...
}

Now I want to render this window into a bitmap before showing it in foreground.

I tried the following things:

  1. Using RenderTargetBitmap

    var window = new MyWindow();
    RenderTargetBitmap bitmap = new((int)window.Width, (int)window.Height, 96, 96, PixelFormats.Pbgra32);
    bitmap.Render(window);
    // window.Show();
    

    I get a full black bitmap. Same thing happens if I call these functions inside the window (bitmap.Render(this)), but it a just render a component of the window (e.g. a Grid), it works fine.

  2. Ensuring window handle

    As someone suggested, I tried WindowInteropHelper to ensure window handle, but it doesn't work.

    var window = new MyWindow();
    var helper = new WindowInteropHelper(window);
    helper.EnsureHandle();
    
    RenderTargetBitmap bitmap = new((int)window.Width, (int)window.Height, 96, 96, PixelFormats.Pbgra32);
    bitmap.Render(window);
    // window.Show();
    
  3. Call Measure(), Arrange() & UpdateLayout() manually

    I called these methods both inside & outside the window class before getting bitmap, it doesn't work either, even with a fixed window size.

I want to know if there's a way to solve my problem or workaround?

发布评论

评论列表(0)

  1. 暂无评论