I'm trying to take a screenshot of the entire desktop, save it into a bitmap, convert the bitmap into a ImageSource and set that ImageSource as a background to a Canvas on which I am going to draw transparent rectangles.
- I tried adding the image directly to the Canvas.
- I tried adding the image as background for the Canvas.
- I even tried adding the image as background to the form and making the canvas transparent, nothing worked.
I started by taking a Desktop snip and converting the image:
Bitmap bitmapImage = new Bitmap(SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height);
myNewImageSource = Miscellaneous.ImageSourceFromBitmap(bitmapImage);
And this is the conversion function, found on another thread:
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject([In] IntPtr hObject);
public static System.Windows.Media.ImageSource ImageSourceFromBitmap(Bitmap bmp)
{
var handle = bmp.GetHbitmap();
try
{
return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally { DeleteObject(handle); }
}
- Setting the image directly:
AddImageToCanvas(0, 0, new System.Windows.Controls.Image() { Source = myNewImageSource });
public void AddImageToCanvas(Int32 x, Int32 y, System.Windows.Controls.Image z)
{
imageHolder.Children.Add(z);
Canvas.SetLeft(z, x);
Canvas.SetTop(z, y);
}
- Adding the image as background for the canvas:
imageHolder.Background = new ImageBrush(){ ImageSource = myNewImageSource };
- Setting the image as form background and making the canvas transparent:
Background = new ImageBrush(){ ImageSource = myNewImageSource }
imageHolder.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 0)) { Opacity = 0 }
//I tried making the background transparent by both setting the Opacity to 0 and trying with argb to set the alpha value to 0, neither worked.
I'm expecting to see a snip of my entire desktop as background for the canvas, but nothing is happening and I'm getting no error. Sometime I just get an entirely black Window.