2014-01-30 167 views
1

我正在嘗試拍攝屏幕截圖並將其設置爲WPF窗口的背景。 這是我的代碼將屏幕截圖轉換爲ImageSource,從位圖轉換時我得到一個NullReferenceException。如何正確地做到這一點?將位圖轉換爲ImageSource

Dim screenSize = Forms.SystemInformation.PrimaryMonitorSize 
    Dim bitmap = New System.Drawing.Bitmap(screenSize.Width, screenSize.Height) 
    Dim g = System.Drawing.Graphics.FromImage(bitmap) 
    g.CopyFromScreen(New System.Drawing.Point(0, 0), New System.Drawing.Point(0, 0), screenSize) 
    g.Flush() 
    Dim c As ImageSourceConverter = New ImageSourceConverter() 
    Dim img As ImageSource = c.ConvertFrom(bitmap) 

回答

2

可以使用CreateBitmapSourceFromHBitmap方法:

Dim hbitmap As IntPtr 
Try  
    hbitmap = bitmap.GetHBitmap() 
    Dim img As ImageSource = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()) 
    ... 
Finally 
    If hbitmap <> IntPtr.Zero Then 
     DeleteObject(hbitmap) 
    End If 
End Try 


... 

<DllImport("gdi32.dll")> _ 
Private Shared Function DeleteObject(hObject As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean 
End Function