Search code examples
c#wpfbitmapbackgroundimagesource

How to convert a Bitmap from memory to an ImageSource then set it as Background for a canvas to draw over it?


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.

  1. I tried adding the image directly to the Canvas.
  2. I tried adding the image as background for the Canvas.
  3. 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); }
}
  1. 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);
}
  1. Adding the image as background for the canvas:
imageHolder.Background = new ImageBrush(){ ImageSource = myNewImageSource };
  1. 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.


Solution

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