Here is the complete program to capture a screenshot, save it to a
file, make some changes(draw a red line), and show it on screen.
#include "iostream"
#include "windows.h"
#include "time.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <io.h>
using namespace std;
int main() {
HDC hScreenDC = GetDC(NULL);//GetWindowDC(0);
HDC hmemDC = CreateCompatibleDC(hScreenDC);
int ScreenWidth = GetDeviceCaps(hScreenDC, HORZRES);
int ScreenHeight = GetDeviceCaps(hScreenDC, VERTRES);
BITMAPINFO bmInfo;
bmInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmInfo.bmiHeader.biWidth = ScreenWidth;
bmInfo.bmiHeader.biHeight = -ScreenHeight;
bmInfo.bmiHeader.biPlanes = 1;
bmInfo.bmiHeader.biBitCount = 24;
bmInfo.bmiHeader.biCompression = BI_RGB;
bmInfo.bmiHeader.biSizeImage = 0;
bmInfo.bmiHeader.biXPelsPerMeter = 0;
bmInfo.bmiHeader.biYPelsPerMeter = 0;
bmInfo.bmiHeader.biClrUsed = 0;
bmInfo.bmiHeader.biClrIm****tant = 0;
HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC,
ScreenWidth,
ScreenHeight);//CreateDIBSection(hScreenDC, &bmInfo, DIB_RGB_COLORS,
0, 0, 0);
BYTE *pbyteBuff = new BYTE[ScreenWidth * ScreenHeight * 3];
HBITMAP oldbits = (HBITMAP)SelectObject(hmemDC, hBitmap);
cout<<"aaaaaaaaa"<<endl;
// copy screen to memory DC
BitBlt(hmemDC, 0, 0, ScreenWidth, ScreenHeight, hScreenDC, 0,
0,
SRCCOPY);
// copy bitmap data into global memory
GetDIBits(hScreenDC, hBitmap, 0, ScreenHeight, pbyteBuff,
&bmInfo,
DIB_RGB_COLORS);
for(int i = 0; i < ScreenWidth; i++)
for(int k = 0; k < 20; k++) {
pbyteBuff[((200 + k) * ScreenWidth + i) * 3 +
0] = 0;
pbyteBuff[((200 + k) * ScreenWidth + i) * 3 +
1] = 0;
pbyteBuff[((200 + k) * ScreenWidth + i) * 3 +
2] = 255;
}
cout<<"bbbbbbbbb"<<endl;
char a;
cin>>a;
SetDIBitsToDevice(hScreenDC, 0, 0, ScreenWidth, ScreenHeight,
0, 0,
0, ScreenHeight, pbyteBuff, &bmInfo, DIB_RGB_COLORS);
cin>>a;
char filename[] = "testScreen01.bmp";
BITMAPFILEHEADER bmFileHeader;
bmFileHeader.bfType = 19778;
bmFileHeader.bfSize = (ScreenWidth * ScreenHeight * 3) +
sizeof(BITMAPINFOHEADER) + 14;
bmFileHeader.bfReserved1 = 0;
bmFileHeader.bfReserved2 = 0;
bmFileHeader.bfOffBits = 54;
// open file and write data
int bmfile = open(filename, O_WRONLY | O_CREAT | O_TRUNC |
O_BINARY,
S_IWRITE);
write(bmfile, &bmFileHeader, 14);
write(bmfile, &bmInfo, 40);
write(bmfile, pbyteBuff, ScreenWidth * ScreenHeight * 3);
// clean up
delete []pbyteBuff;
close(bmfile);
DeleteObject(hBitmap);
DeleteDC(hmemDC);
ReleaseDC(0, hScreenDC);
return 0;
}


|