Easy way to create a screen dump of all the screens attached to the system. You need System.Windows.Forms and System.Drawing to pull it off.
My colleague Niklas Dahlman (twitter, blog) coded an elegant piece of code the other day. He can be a bit hesitant to take credit so I’ll post it for him. ;~)
Our client dreamt up the idea to screen dump the current screen(s) when ever our app does a nose dive. We are currently working with a foreign exchange bank building a test framework for their very large system. Interesting work for sure and challenging!
The challenge is that we run a lot of tests on test servers and part of the tests is to have our test scripts drive the UI of the banks applications. If ever a test should fail (yeah – like that will ever happen) we want to make a screen dump of what went on graphically at that time. The screen capture is elegantly added to the test results for the test run. Very nice!
The elegant piece of code just has to be shared. Read it and enjoy!
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
namespace Utilities
{
/// <summary>
/// Utility to take a screenshot
/// </summary>
public class ScreenGrabber
{
private static Bitmap _bmpScreenshot;
private static Graphics _gfxScreenshot;
/// <summary>
/// grab the screen, generate a filename and save
/// </summary>
/// <returns>array of path(s) to the saved file(s)</returns>
public string[] GrabIt()
{
string[] fileNames = new string[Screen.AllScreens.Length];
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
Screen scr = Screen.AllScreens[i];
http://twitter.com/noopman string fileName = Path.GetTempFileName();
_bmpScreenshot = new Bitmap(scr.Bounds.Width, scr.Bounds.Height, PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap
_gfxScreenshot = Graphics.FromImage(_bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner
_gfxScreenshot.CopyFromScreen(scr.Bounds.X, scr.Bounds.Y, 0, 0,
scr.Bounds.Size, CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen
_bmpScreenshot.Save(fileName, ImageFormat.Png);
string pngFileName = string.Concat(fileName, ".png");
File.Copy(fileName, Path.Combine(System.Environment.CurrentDirectory, Path.GetFileName(pngFileName)));
}
return fileNames;
}
}
[TestClass]
public class ScreenGrabberTests
{
[TestMethod]
public void GrabAllScreensTest()
{
ScreenGrabber sg = new ScreenGrabber();
string[] fileNames = sg.GrabIt();
Assert.IsTrue(fileNames.Length >= 1);
}
}
}
Cheers,
M.
http://twitter.com/noopman
posted @ Sunday, May 10, 2009 10:25 PM