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

For example I have a WPF window:public class MyWindow : Window{public MyWindow(){InitializeStyle();In

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744278692a4566462.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信