另外使用createfile函数将捕捉后的图片储存为文件
#include <Windows.h> #include <stdio.h> #include <assert.h> void scrshot() { Sleep(1000); BITMAP bmpScreen; HWND hwnd = GetDesktopWindow(); HDC hdc = GetWindowDC(hwnd); HDC hdcMem = CreateCompatibleDC(hdc); int cx = GetDeviceCaps(hdc, HORZRES); int cy = GetDeviceCaps(hdc, VERTRES); HBITMAP hbitmap(NULL); hbitmap = CreateCompatibleBitmap(hdc, cx, cy); SelectObject(hdcMem, hbitmap); BitBlt(hdcMem, 0, 0, cx, cy, hdc, 0, 0, SRCCOPY); CURSORINFO cursor = { sizeof(cursor) }; GetCursorInfo(&cursor); if (cursor.flags == CURSOR_SHOWING) { RECT rect; GetWindowRect(hwnd, &rect); ICONINFO info = { sizeof(info) }; GetIconInfo(cursor.hCursor, &info); const int x = cursor.ptScreenPos.x - rect.left - rect.left - info.xHotspot; const int y = cursor.ptScreenPos.y - rect.top - rect.top - info.yHotspot; BITMAP bmpCursor = { 0 }; GetObject(info.hbmColor, sizeof(bmpCursor), &bmpCursor); DrawIconEx(hdcMem, x, y, cursor.hCursor, bmpCursor.bmWidth, bmpCursor.bmHeight, 0, NULL, DI_NORMAL); GetObject(hbitmap, sizeof(BITMAP), &bmpScreen); BITMAPFILEHEADER bmfHeader; BITMAPINFOHEADER bi; bi.biSize = sizeof(BITMAPINFOHEADER); bi.biWidth = bmpScreen.bmWidth; bi.biHeight = bmpScreen.bmHeight; bi.biPlanes = 1; bi.biBitCount = 24; bi.biCompression = BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrUsed = 0; bi.biClrImportant = 0; DWORD dwBmpSize = ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpScreen.bmHeight; //位图大小 // Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that // call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc // have greater overhead than HeapAlloc. HANDLE hDIB = GlobalAlloc(GHND, dwBmpSize); char *lpbitmap = (char *)GlobalLock(hDIB); //GetDIBits函数检索指定兼容位图的位, //并使用指定的格式将其作为dib复制到缓冲区中。 GetDIBits(hdc, hbitmap, 0, (UINT)bmpScreen.bmHeight, lpbitmap, //指向接收位图数据的缓冲区的指针。如果此参数为空,则函数将位图的尺寸和格式传递给lpbi参数指向的bitmapinfo结构。 (BITMAPINFO *)&bi, //指向指定DIB数据所需格式的BitmapInfo结构的指针 DIB_RGB_COLORS); // A file is created, this is where we will save the screen capture. HANDLE hFile = CreateFile("captureqwsx1.bmp", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // 将headers的大小添加到位图的大小中, 以获取总文件大小 DWORD dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); //偏移到实际位图位开始的位置。 bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER); //Size of the file bmfHeader.bfSize = dwSizeofDIB; //bfType must always be BM for Bitmaps bmfHeader.bfType = 0x4D42; //BM DWORD dwBytesWritten = 0; WriteFile(hFile, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL); WriteFile(hFile, (LPSTR)&bi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL); WriteFile(hFile, (LPSTR)lpbitmap, dwBmpSize, &dwBytesWritten, NULL); } } int main() { scrshot(); return 0; }