Reputation: 20202
I try to create a screenshot like described here:
private Graphics takeScreenshot()
{
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
return gfxScreenshot;
}
How can I show it in my form after it is taken? I tried to display it inside a pictureBox:
Graphics screenshot = takeScreenshot();
pictureBox1.Image = screenshot;
But I get:
Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Drawing.Graphics' to 'System.Drawing.Image' SRAT C:\Users\Edd\documents\visual studio 2017\Projects\SRAT\SRAT\Form1.cs 20 Active
and this answer says that it is not possible to convert it
Upvotes: 2
Views: 1067
Reputation: 103437
A Graphics
object is a sort of wrapper around an image that lets you draw on the image. They are usually temporary, and don't actually own the pixels that you're drawing.
In your case, gfxScreenshot
is just providing the ability to draw onto bmpScreenshot
, which is where the image actually lives in memory.
You should throw away the Graphics
and return the Bitmap
:
private Bitmap TakeScreenshot()
{
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
using (var gfxScreenshot = Graphics.FromImage(bmpScreenshot))
{
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
}
return bmpScreenshot;
}
Then you can assign the bitmap to a PictureBox
:
Bitmap screenshot = TakeScreenshot();
pictureBox1.Image = screenshot;
Upvotes: 3