1

我想获取一个屏幕截图并将其保存为整个屏幕的 png 格式。我怎样才能做到这一点?

我可以使用截图工具库来完成这个吗?互联网上有一些教程向您展示如何使用 Windows 窗体执行此操作,并且图像采用位图格式。

4

1 回答 1

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");
于 2012-04-04T18:29:36.213 回答