2017-08-30 44 views
1

我尝试创建像描述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; 
} 

我怎样才能显示它在我的形式拍摄后? 我试图显示它一个PictureBox内:

Graphics screenshot = takeScreenshot(); 
pictureBox1.Image = screenshot; 

,但我得到:

严重性代码说明项目文件的线路抑制状态 错误CS0029无法隐式转换类型“System.Drawing.Graphics” 以 '为System.Drawing.Image' SRAT C:\用户\埃德\的文档\ Visual Studio的 2017年\项目\ SRAT \ SRAT \ Form1.cs的20个活动

的d this answer表示无法将其转换为

+2

不要返回'Graphics',回'bmpScreenshot相反。 – Blorgbeard

回答

1

A Graphics对象是围绕图像的一种包装,可让您在图像上绘图。它们通常是暂时的,并且实际上并不拥有您正在绘制的像素。

在你的情况下,gfxScreenshot只是提供了吸引到bmpScreenshot的能力,这是图像实际存在于内存中的地方。

你应该扔掉Graphics并返回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; 
} 

然后您可以将位图分配给PictureBox

Bitmap screenshot = TakeScreenshot(); 
pictureBox1.Image = screenshot; 
+0

这完美的作品!谢谢!现在我有一个想法如何工作。 – Black