HDC hdcScreen, hdcCompatible; hdcScreen = CreateDC("DISPLAY", NULL, NULL, NULL); hdcCompatible = CreateCompatibleDC(hdcScreen); int nWidth = GetDeviceCaps(hdcScreen, HORZRES); int nHeight = GetDeviceCaps(hdcScreen, VERTRES); HBITMAP hbmScreen; hbmScreen = CreateCompatibleBitmap(hdcScreen, nWidth, nHeight); if (SelectObject(hdcCompatible, hbmScreen)) { BitBlt(hdcCompatible, 0,0, nWidth, nHeight, hdcScreen, 0,0, SRCCOPY); //位图信息头 BITMAPINFOHEADER bih = {0}; bih.biBitCount = GetDeviceCaps(hdcCompatible, BITSPIXEL); //显示位色 bih.biCompression = BI_RGB; //压缩模式 bih.biHeight = nHeight; //高度 bih.biWidth = nWidth; //宽度 bih.biPlanes = 1; //must be 1. bih.biSize = sizeof(BITMAPINFOHEADER); //bih's size bih.biSizeImage = (bih.biWidth*bih.biBitCount+31)/32*4*bih.biHeight; //位图大小计算公式 //位图文件头 BITMAPFILEHEADER bfh = {0}; bfh.bfType = (WORD)0x4d42; //Specifies the file type, must be BM bfh.bfOffBits = sizeof(bfh) + sizeof(bih); //BMPHEAD Offset bfh.bfSize = bfh.bfOffBits + bih.biSizeImage; //所有内容大小 //拷贝到缓冲区 BYTE *buff = new BYTE[bih.biSizeImage]; GetDIBits( hdcCompatible, // handle to DC hbmScreen, // handle to bitmap 0, // first scan line to set bih.biHeight, // number of scan lines to copy buff, // array for bitmap bits (LPBITMAPINFO)&bih, // bitmap data buffer DIB_RGB_COLORS // RGB or palette index ); //写位图文件 FILE *file; file = fopen("TESTBMP.bmp", "w+b"); //以二进制打开文件 fwrite(&bfh, 1, sizeof(bfh), file); //写入位图文件头 fwrite(&bih, 1, sizeof(bih), file); //写入位图信息头 fwrite(buff, 1, bih.biSizeImage, file); //写入位图数据 fclose(file); DeleteObject(hdcCompatible); //释放DC }