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 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); }
}
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);
}
imageHolder.Background = new ImageBrush(){ ImageSource = myNewImageSource };
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.
For those that need this, I forgot to actually take the screenshot. Here's my code for it:
Graphics g = Graphics.FromImage(bitmapImage);
g.CopyFromScreen(0, 0, 0, 0, bitmapImage.Size);