windows 屏幕截取

3 views
Skip to first unread message

裴国兴

unread,
Nov 8, 2009, 1:31:05 AM11/8/09
to btload
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int InitializeBuffer(const BITMAPINFO *bitmapInfo, char *bmpbuf,
size_t *byteCount)
{
size_t width, height;
BITMAPINFOHEADER ihdr = bitmapInfo->bmiHeader;
width = ihdr.biWidth;
height = abs(ihdr.biHeight);

size_t width3 = (width*ihdr.biBitCount/8+3)&~0x3;
BITMAPFILEHEADER fhdr;
memcpy(&fhdr.bfType, "BM", 2);
fhdr.bfReserved1 = 0;
fhdr.bfReserved2 = 0;
fhdr.bfOffBits = sizeof(BITMAPFILEHEADER);
fhdr.bfOffBits += sizeof(BITMAPINFOHEADER);

*byteCount = width3*height;
fhdr.bfSize = width3*height+fhdr.bfOffBits;
memcpy(bmpbuf, &fhdr, sizeof(fhdr));
memcpy(bmpbuf+sizeof(fhdr), &ihdr, sizeof(ihdr));
return sizeof(fhdr)+sizeof(ihdr);
}

void BitmapToFile(const BITMAPINFO *pBitmapInfo, const void *pvBits,
const char *path)
{
char buffer[8192];
FILE *fpout = fopen(path, "wb");
if (fpout == NULL)
return;
size_t count = 0;
fwrite(buffer, InitializeBuffer(pBitmapInfo, buffer, &count), 1,
fpout);
fwrite(pvBits, count, 1, fpout);
fclose(fpout);
}

BITMAPINFO *InitializeBITMAPINFO(HDC hDC, BITMAPINFO *info)
{
int Width = GetDeviceCaps(hDC, HORZRES);
int Height = GetDeviceCaps(hDC, VERTRES);
int BitPerPixel = GetDeviceCaps(hDC, BITSPIXEL);

memset(info, 0, sizeof(BITMAPINFO));
info->bmiHeader.biBitCount = BitPerPixel>24?24:BitPerPixel;
info->bmiHeader.biCompression = BI_RGB;
info->bmiHeader.biHeight = Height;
info->bmiHeader.biPlanes = 1;
info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info->bmiHeader.biWidth = Width;
return info;
}

int main(int argc, char* argv[])
{
FreeConsole();
HDC hDC = GetDC(NULL);
HDC hMemDC = CreateCompatibleDC(hDC);
BITMAPINFO bitmapInformation;
void *pvBits = NULL;
HBITMAP hBitmap = CreateDIBSection(hDC, InitializeBITMAPINFO(hDC,
&bitmapInformation),
DIB_RGB_COLORS, &pvBits, NULL, 0);
HGDIOBJ hOldObj = SelectObject(hMemDC, hBitmap);
BitBlt(hMemDC, 0, 0, bitmapInformation.bmiHeader.biWidth,
abs(bitmapInformation.bmiHeader.biHeight), hDC, 0, 0, SRCCOPY);
BitmapToFile(&bitmapInformation, pvBits, "snapshot.bmp");
SelectObject(hMemDC, hOldObj);
DeleteObject(hBitmap);
DeleteDC(hMemDC);
ReleaseDC(NULL, hDC);
AllocConsole();
return 0;
}


用于windows下的屏幕扑做
Reply all
Reply to author
Forward
0 new messages