
Introduction
The following subjects are discussed in this article:
- Capturing an image of the desktop or its work area.
- Capturing an image of a control or its client area.
- Capturing an image of what's underneath a control or its client area.
- Converting images from one format to another.
- Converting an image to usable icon.
Background
Several C# and C++ articles are available discussing desktop capture. This article generalizes from there and presents a testbed for loading, capturing, and saving images in various graphical formats including conversion of an image to a usable icon.
Captured images are specified areas of GDI windows such as the desktop or a GDI+ control. A GDI (Graphical Device Interface) window is specified by a window handle. To operate on a GDI+ object (basically a .NET control) using a GDI method, we need to use its GDI window handle. Fortunately, it is available.
...
System.Windows.Forms.Control ctl = new System.Windows.Forms.Control();
System.IntPtr wndHandle = ctl.Handle;
...
Code Organization
The solution consists of two projects;
- A C# library containing the capture methods (Capture.cs), \ the interop methods (Dll.cs), as well as some debug and sound methods, and
- A testing form (TestCapture.cs) to exercise the capture methods.
Module Dll.cs
This module defines entry points to methods contained in various DLLs. To simplify access, a namespace called Dll
is defined whose class names are the same as the DLLs to be accessed. Each class then defines the desired interop DLL entry points and equivalent C# methods.
Example class defining C# accessible entry points for a DLL
...
public class GDI32
{
public const int SRCCOPY = 13369376;
[DllImport("gdi32.dll", EntryPoint="DeleteDC")]
public static extern IntPtr DeleteDC(IntPtr hDc);
[DllImport("gdi32.dll", EntryPoint="DeleteObject")]
public static extern IntPtr DeleteObject(IntPtr hDc);
[DllImport("gdi32.dll", EntryPoint="BitBlt")]
public static extern bool BitBlt(IntPtr hdcDest,int xDest,
int yDest,int wDest,int hDest,IntPtr hdcSource,
int xSrc,int ySrc,int RasterOp);
[DllImport("gdi32.dll", EntryPoint="CreateCompatibleBitmap")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc,
int nWidth, int nHeight);
[DllImport("gdi32.dll", EntryPoint="CreateCompatibleDC")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll", EntryPoint="SelectObject")]
public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp);
}
...
Rather than directly accessing the interop methods from other projects, access in this solution is isolated to the classes in the C# library such as the Capture
class.
...
Dll.USER32.ReleaseDC(wndHWND,wndHDC);
Dll.GDI32.DeleteDC(capHDC);
Dll.GDI32.DeleteObject(capBMP);
...
Module Capture.cs
GDI Window Capture
The underlying method used by other capture methods is shown below. This method captures an image within a specified rectangle within a specified window. The window is specified by a GDI window handle. The image is returned as a .NET bitmap.
The method operates as follows. First, a window device context is procured. Second, using the window device context, a compatible capture device context is created, and a GDI bitmap is created and associated with this capture device context. Third, the specified rectangle in the window device context is copied to the capture device context thus populating the GDI bitmap. Finally, the GDI bitmap is converted to a GDI+ bitmap and returned to the caller.
public static Bitmap Window(IntPtr wndHWND,
int x, int y, int width, int height)
{
IntPtr wndHDC = USER32.GetDC(wndHWND);
IntPtr capHDC = GDI32.CreateCompatibleDC(wndHDC);
IntPtr capBMP = GDI32.CreateCompatibleBitmap(wndHDC, width, height);
if (capBMP == IntPtr.Zero)
{
USER32.ReleaseDC(wndHWND,wndHDC);
GDI32.DeleteDC(capHDC);
return null;
}
IntPtr prvHDC = (IntPtr)GDI32.SelectObject(capHDC,capBMP);
GDI32.BitBlt(capHDC,0,0,width,height,wndHDC,x,y,GDI32.SRCCOPY);
GDI32.SelectObject(capHDC,prvHDC);
Bitmap bmp = System.Drawing.Image.FromHbitmap(capBMP);
USER32.ReleaseDC(wndHWND,wndHDC);
GDI32.DeleteDC(capHDC);
GDI32.DeleteObject(capBMP);
return bmp;
}
Desktop Capture
The desktop capture methods (Desktop
and DesktopWA
) are shown below.
Method Desktop
captures the entire desktop. It picks up the width and height of the desktop, a window handle for the desktop and then uses capture method Window
to return a bitmap of the desktop. The width and height are procured using interop routines. This information can also be attained using the method System.Windows.Forms.Screen.PrimaryScreen.Bounds
.
Method DesktopWA
captures the working area of the desktop. It picks up the bounds of the desktop working area based on a specified control in that working area and then uses capture method Window
to return a bitmap of the desktop.
public static Bitmap Desktop()
{
int width = USER32.GetSystemMetrics(USER32.SM_CXSCREEN);
int height = USER32.GetSystemMetrics(USER32.SM_CYSCREEN);
IntPtr desktopHWND = USER32.GetDesktopWindow();
return Window(desktopHWND,0,0,width,height);
}
public static Bitmap DesktopWA(Control ctl)
{
Rectangle wa = Screen.GetWorkingArea(ctl);
IntPtr desktopHWND = USER32.GetDesktopWindow();
return Window(desktopHWND,wa.X,wa.Y,wa.Width,wa.Height);
}
Control Capture
The control capture method is Control
. The first method Control
captures the entire control. The second method Control
captures a specified portion of the control or what's underneath the control.
When capturing what's beneath a control, the desired area is converted to screen coordinates and a window handle to the screen (desktop) is utilized for the capture. The window handle for the control cannot be used since the desired area is on the screen under the control. To perform this capture and procure the desired bitmap, the control must be hidden prior to capture.
When capturing an area on the control, the desired area is converted to control coordinates and a window handle for the control is utilized for the capture.
public static Bitmap Control(System.Windows.Forms.Control ctl)
{
return Control(ctl,false,false);
}
public static Bitmap Control(System.Windows.Forms.Control ctl
,bool client,bool under)
{
Bitmap bmp;
Rectangle ctlR;
Rectangle scrR;
if (client)
{
ctlR = ctl.ClientRectangle;
scrR = ctl.RectangleToScreen(ctlR);
}
else
{
scrR = ctl.Bounds;
if (ctl.Parent != null)
scrR = ctl.Parent.RectangleToScreen(scrR);
ctlR = ctl.RectangleToClient(scrR);
}
if (under)
{
bool prvV = ctl.Visible;
if (prvV)
{
ctl.Visible = false;
Thread.Sleep(m_HDelay);
)
IntPtr desktopHWND = USER32.GetDesktopWindow();
bmp = Window(desktopHWND,scrR);
if (ctl.Visible != prvV)
ctl.Visible = prvV;
}
else
{
bmp = Window(ctl.Handle,ctlR);
}
return bmp;
}
ImageCapture.cs
The image capture form allows images to be loaded, saved, captured, and converted. It handles one image at a time and does not as yet include image editing functions. It will, optionally, retain the aspect ratio of an image. Load and save support a number of image formats allowing image format conversion. And, images can be converted and saved as usable icons. The form was used for testing, and has very elemental error checking and recovery capabilities.
Image Capture
Action menu items control image capture. Desktop or desktop area image capture is accomplished by clicking the appropriate action menu item, "Capture Desktop" or "Capture Desktop Work Area" respectively.
Partial desktop image captures are done using the viewport. The viewport is the client area of the form. To use the viewport, it must first be opened. This is done by clicking action menu item "Open Viewport". Opening the viewport causes the form's transparency key to be set to the background color of the form. This makes the area underneath the client area of the form visible to the user. The user moves the form over and sizes the form to encompass the desired selection. Capture of the image is accomplished by clicking action menu item "Capture View". This causes the view to be captured and the viewport to be closed.
Prior to loading or capturing another image, the current image must be saved or released. The action menu item "Release View" will dispose off the current image.
Image Load
An image may be loaded from a file. For images other than icons, the method Image.FromFile
is utilized to input the image. This method automatically detects the format of the image upon input, without requiring the user to specify that format. The image is then converted to a bitmap.
Icons are special cased. Icons are input using the Icon
constructor, and then converted to a bitmap.
private void miLoad_Click(object sender, System.EventArgs e)
{
if (UnsavedBM())
return;
CloseViewport();
DialogResult dr = ofd.ShowDialog(this);
if (dr != DialogResult.OK)
return;
string fn = ofd.FileName;
int idx = fn.LastIndexOf("\\"); // get last backslash
sfd.InitialDirectory = (idx <= 0)? "" : fn.Substring(0,idx);
sfd.FileName = fn; // make default for save
Dispose(capBM); // dispose of previous bitmap (if any)
idx = fn.LastIndexOf(".") + 1; // find start of extension
string ext = (idx > 0) && (idx < fn.Length)? fn.Substring(idx) : "";
if (ext.ToLower().Equals("ico")) // if file is an icon
{
this.Icon = new Icon(fn); // read new form icon from file
capBM = this.Icon.ToBitmap(); // convert to bitmap
}
else // if file not an icon
capBM = new Bitmap(Image.FromFile(fn));// read bitmap from file
PicInCtl(curCtl,false); // place new image in current control
capBMSaved = true; // image has been saved, it came from a file
Play("LoadView.wav"); // play load view sound
} // end action miLoad_Click
Image Display
A loaded or captured image is manipulated internally as a Bitmap
. It should be noted that a Bitmap
is based on an Image
and can thus be thought of as an image when necessary. Essentially, the current image is displayed as the background of the client area of the form. When the form is resized, the image is resized to fit within its client area. If the image aspect ratio is being preserved, the normal case, then an aspect sized version of the image will be fit within the client area of the form. No image significance is lost since the original bitmap is preserved.
Image Save
An image may be saved to a file. For images other than icons, the Bitmap
instance method Save
is utilized to output the image. This method supports a large number of image formats. However, the image format must be explicitly specified when invoking Bitmap
instance method Save
. A filter is used in the save file dialog to allow the user to select the image format.
private void miSave_Click(object sender, System.EventArgs e)
{
if (capBM == null)
return;
DialogResult dr = sfd.ShowDialog(this);
if (dr != DialogResult.OK)
return;
string fn = sfd.FileName;
if (fn.Equals(""))
{
Play("Error.wav");
MessageBox.Show("No filename specified, nothing saved");
return;
}
ImageType it = ImageType.SetImageType(sfd.FilterIndex-1);
if (it.format == ImageFormat.Icon)
{
Icon = BitmapToIcon(capBM,aspect);
Stream s = sfd.OpenFile();
Icon.Save(s);
s.Close();
}
else
capBM.Save(fn,it.format);
capBMSaved = true;
Play("SaveView.wav");
}
Image to Icon
An image may be saved as an icon. A usable icon is based on a small bitmap. The maximum size of this bitmap is determined by display resolution and color support. For the purposes of this demo, a display supporting at least 256 colors or more was assumed. For this display assumption, the maximum bitmap size is 96 by 96. Converting the image bitmap to a bitmap for the icon is not a problem. However, preserving the image aspect ratio is a problem.
The choice made in this demo for icon aspect preservation was to drop significance in the longest direction. In other words, a bitmap was formed that was 96 pixels in the shortest direction and more than this in the longest direction. The icon bitmap was then extracted from this bitmap using a centering rectangle thus dropping some significance along both outer edges for the longest direction. To preserve aspect without losing significance, the image should be edited and/or cropped into a square. This can be done in an external image editor since these features don't currently exist in ImageCapture.
private Icon BitmapToIcon(Bitmap obm,bool preserve)
{
Bitmap bm;
if (!preserve)
bm = new Bitmap(obm,ICON_W,ICON_H);
else
{
Rectangle rc = new Rectangle(0,0,ICON_W,ICON_H);
if (obm.Width >= obm.Height)
{
bm = new Bitmap(obm,(ICON_H*obm.Width)/obm.Height,ICON_H);
rc.X = (bm.Width - ICON_W) / 2;
if (rc.X < 0) rc.X = 0;
}
else
{
bm = new Bitmap(obm,ICON_W,(ICON_W*obm.Height)/obm.Width);
rc.Y = (bm.Height - ICON_H) / 2;
if (rc.Y < 0) rc.Y = 0;
}
bm = bm.Clone(rc,bm.PixelFormat);
}
Icon icon = Icon.FromHandle(bm.GetHicon());
bm.Dispose();
return icon;
}
Points of Interest
- Aspect Preservation - Abandoned Approach. Keying off form size changes to then modify the client area of the form for aspect preservation created an out of order resonating series of form size changes that led to unfortunate behavior. Even though these issues were eventually overcome, the approach was abandoned as too cumbersome.
- GDI Window Handles - Since a GDI window handle can be used to conger up the associated GDI+ control, using the
Control.FromHandle
method, it seemed possible there might be a GDI+ control available for the desktop that could be accessed using this method. Of course, the results after testing this hypothesis were disappointing. Although the test crashes were variously reported by the debugger, no GDI+ control for the desktop was ever forthcoming using this technique.
- Image Beneath Control - Various methods were tested to gather the image beneath a control. Timing issues arose during some of the early tests. A variable delay was introduced to overcome this problem. The code still has a 5ms delay to allow the control being hidden to drop out of the desktop bitmap. This delay may no longer be required. More testing needs to be done in this regard.
History
01/31/2004 - Initial release.