2016-11-07 58 views
1

我有一個包含Winform和WPF元素集合的WPF面板(在WPF應用程序中)。 Winform元素通過WindowsFormsHost託管。使用Winform和WPF元素從面板創建BitmapSource

我需要創建整個面板的BitmapSource(就像它一樣),所以我可以操作它/保存/打印出來。

創建WPF元素的BitmapSource不是問題,但Winform元素沒有呈現(它們應該是隻有一個空白空間)。那

一個例子:

void GetBitmapSource(FrameworkElement element) 
{ 
    var matrix = PresentationSource.FromVisual(element).CompositionTarget.TransformToDevice; 
    double dpiX = 96.0 * matrix.M11; 
    double dpiY = 96.0 * matrix.M22; 
    var bitmapSource = new RenderTargetBitmap((int)element.ActualWidth + 1, (int)element.ActualHeight + 1, dpiX, dpiY, PixelFormats.Pbgra32); 
    bitmapSource.Render(element); 
    return bitmapSource; 
} 

這將打印WPF元素就好了,但忽略Winform的內容。我如何包含它?

下圖顯示了左側的Tabpanel和右側的BitmapSource。注意Winform矩形的內容是空的。 Tabpanel on the left and BitmapSource on the right.

+1

也許有所幫助:http://stackoverflow.com/q/1756954/1136211 – Clemens

+0

我發現從托馬斯Levesque的一種解決方案,他的回答[這裏](http://stackoverflow.com/a/1756976/3064934 )。 – Daltons

回答

1

如何獲取完整的屏幕截圖,然後將其剪切爲元素?

BitmapSource ScreenShot(int x, int y, int width, int height) 
{ 
    using (var screenBitmap = new Bitmap(width,height,System.Drawing.Imaging.PixelFormat.Format32bppArgb)) 
    { 
     using (var g = Graphics.FromImage(screenBitmap)) 
     { 
      g.CopyFromScreen(x, y, 0, 0, screenBitmap.Size); 
      var result = Imaging.CreateBitmapSourceFromHBitmap(
       screenBitmap.GetHbitmap(), 
       IntPtr.Zero, 
       Int32Rect.Empty, 
       BitmapSizeOptions.FromEmptyOptions()); 
      return result; 
     } 
    } 
} 
+0

這是如此骯髒,它應該在一個巨大的「NSFW」警告在頂部的擾流盒......但**它的作品**! (我必須打印一個模板WPF控件,它的可視化樹中有一個Windows窗體託管控件,這是我發現的唯一不會留下黑色或白色矩形的控件。很遺憾,輸出質量很差,但乞丐不能選擇。) –