2012-04-04 61 views
1

我想獲得一個屏幕截圖並將其保存爲整個屏幕的png格式。我怎樣才能做到這一點?png格式的桌面捕捉

我可以使用Snipping Tool庫來實現這個嗎?在互聯網上有一些教程,告訴你如何使用Windows窗體來完成此操作,並且圖像採用位圖格式。

回答

8

這裏有一個方法來捕獲任何屏幕的內容。用法

private static void CaptureScreen(Screen window, string file) 
    { 
     try 
     { 
      Rectangle s_rect = window.Bounds; 
      using (Bitmap bmp = new Bitmap(s_rect.Width, s_rect.Height)) 
      { 
       using (Graphics gScreen = Graphics.FromImage(bmp)) 
        gScreen.CopyFromScreen(s_rect.Location, Point.Empty, s_rect.Size); 
       bmp.Save(file, System.Drawing.Imaging.ImageFormat.Png); 
      } 
     } 
     catch (Exception) { /*TODO: Any exception handling.*/ } 
    } 

例子:

CaptureScreen(Screen.PrimaryScreen, @"B:\exampleScreenshot.png"); 

編輯:說回這個,後來我意識到它可能更有助於從函數返回一個Image對象,所以你可以選擇如何使用捕捉位圖。

我也已經使該功能現在更強大一些,以便它可以捕捉多個屏幕(即在多顯示器設置中)。它應該適應不同高度的屏幕,但我不能測試這個我自己。

public static Image CaptureScreens(params Screen[] screens) { 
    if (screens == null || screens.Length == 0) 
     throw new ArgumentNullException("screens"); 

    // Order them in logical left-to-right fashion. 
    var orderedScreens = screens.OrderBy(s => s.Bounds.Left).ToList(); 
    // Calculate the total width needed to fit all the screen into a single image 
    var totalWidth = orderedScreens.Sum(s => s.Bounds.Width); 
    // In order to handle screens of different sizes, make sure to make the Bitmap large enough to fit the tallest screen 
    var maxHeight = orderedScreens.Max(s => s.Bounds.Top + s.Bounds.Height); 

    var bmp = new Bitmap(totalWidth, maxHeight); 
    int offset = 0; 

    // Copy each screen to the bitmap 
    using (var g = Graphics.FromImage(bmp)) { 
     foreach (var screen in orderedScreens) { 
      g.CopyFromScreen(screen.Bounds.Left, screen.Bounds.Top, offset, screen.Bounds.Top, screen.Bounds.Size); 
      offset += screen.Bounds.Width; 
     } 
    } 

    return bmp; 
} 

新的例子:

// Capture all monitors and save them to file 
CaptureScreens(Screen.AllScreens).Save(@"C:\Users\FooBar\screens.png");