Follow-up on Screen Capturing in Whidbey, I'm a fool who doesn't do all of his homework...
In my previous article If you could pick the reason why GDI should be .NET accessible, what would it be? I talked about the new GDI namespace. Now, while I was searching and searching for a way to do screen captures on the GDI classes, they instead added the screen capture to the actual Graphics class. I could go into why this is such a band-aid, but I won't. Instead I'll show you how to use it, then talk about how it is a band-aid ;-)
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
public class ScreenCap {
private static void Main(string[] args) {
if ( args.Length < 1 ) {
return;
}
string fileName = args[0];
ScreenCapture(fileName);
}
private static void ScreenCapture(string fileName) {
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics gfx = Graphics.FromImage(bmp);
gfx.CopyFromScreen(0, 0, 0, 0, bmp.Size);
gfx.Dispose();
bmp.Save(fileName, ImageFormat.Jpeg);
}
}
The above code makes a screen capture. It takes a while to load and run, which I don't find very amusing, but what the heck, I can't complain. You can extend this with my previous article to show how you might first copy the screen, modify it, and then write it back out for a screen saver. I'll do something along these lines soon, since I have a large amount of GDI+ filters written that would be cool to render animated over the desktop.
Now I want to talk about how much of a band-aid this is. Any copy operation from the screen is doing a BitBlt somewhere. A BitBlt can and should be allowed between ANY two surfaces, but they are limiting access to the copy operation to only screen surfaces, and not allowing blt's between offscreen surfaces. Rather than give a generic method for copying from any hDC or device context, which would have been really nice, especially for DirectX + GDI interfacing, they instead give you an operation to only copy the entire screen. I'll stop now. Enjoy your screen capture code and watch for my upcoming screen saver section.