2017-08-30 76 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