The below is not my code, I found it some time ago on this board (I think one of the senior members post it). I remember testing it and it worked fine;
Code:
void CaptureWindow ( HWND hwnd )
{
RECT rect;
HDC src_hdc;
HDC dst_hdc;
HBITMAP hbitmap;
BITMAPINFO bi;
LPBYTE pBits;
int w;
int h;
HANDLE file_handle;
GetClientRect ( hwnd, &rect );
w = rect.right - rect.left;
h = rect.bottom - rect.top;
src_hdc = GetDC ( hwnd );
dst_hdc = CreateCompatibleDC ( src_hdc );
ZeroMemory ( &bi, sizeof ( bi ) );
bi.bmiHeader.biSize = sizeof ( bi.bmiHeader );
bi.bmiHeader.biHeight = h;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 24;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = ((w * bi.bmiHeader.biBitCount +31)& ~31) / 8 * h;
hbitmap = CreateDIBSection ( src_hdc, &bi, DIB_RGB_COLORS, (LPVOID *) &pBits, NULL, 0 );
SelectObject ( dst_hdc, hbitmap );
if ( BitBlt ( dst_hdc, 0, 0, w, h, src_hdc, rect.left, rect.top, SRCCOPY ) ) {
file_handle = CreateFile ( "grab.bmp", GENERIC_WRITE, FILE_SHARE_WRITE,
NULL,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
if ( file_handle != INVALID_HANDLE_VALUE ) {
DWORD dwRet = 0;
BITMAPFILEHEADER bfh;
ZeroMemory ( &bfh, sizeof ( bfh ) );
bfh.bfType = 0x4D42;
bfh.bfOffBits = sizeof ( BITMAPFILEHEADER ) + sizeof ( BITMAPINFOHEADER );
bfh.bfSize = bi.bmiHeader.biSizeImage + bfh.bfOffBits;
WriteFile ( file_handle, &bfh, sizeof ( bfh ), &dwRet, NULL);
WriteFile ( file_handle, &bi.bmiHeader, sizeof ( bi.bmiHeader ), &dwRet, NULL );
WriteFile ( file_handle, pBits, bi.bmiHeader.biSizeImage, &dwRet, NULL );
}
CloseHandle ( file_handle );
DeleteDC ( dst_hdc );
DeleteObject ( hbitmap );
ReleaseDC ( hwnd, src_hdc );
}
}
If I remember, it was something like CaptureWindow(GetDesktopWindow()); to get the desktop.