2015-03-13 116 views
1

我們需要在後臺線程中創建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但沒有成功(不完全理解該課程的目的)。

回答

0

這是可能的,你缺少的位可能是測量和控制的安排:

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); 
     } 

    } 
+0

你的榜樣作品 - 但在我的代碼我使用的圖像和一個不工作:屏幕截圖始終是白色的。我從Image派生出來,並且覆蓋了OnRender,看看是否有人被調用 - 事實上它是(callstack從Arrange()調用開始)。 – 2015-03-16 13:24:31

+0

對不起,這是我的錯誤 - 我加載的圖像沒有複製到輸出目錄,我認爲它會從程序集本身加載(該文件被標記爲「資源」)。因此,圖像無法加載。 – 2015-03-16 13:57:42