1 void CMyPrntScrDlg::Screen(const char* filename)
2 {
3 //GetDC();
4 CDC *pDC;//屏幕DC
5 pDC = CDC::FromHandle(::GetDC(NULL));//获取当前整个屏幕DC
6 int BitPerPixel = pDC->GetDeviceCaps(BITSPIXEL);//获得颜色模式
7 int Width = pDC->GetDeviceCaps(HORZRES);
8 int Height = pDC->GetDeviceCaps(VERTRES);
9
10 /*printf("当前屏幕色彩模式为%d位色彩\n", BitPerPixel);
11 printf("屏幕宽度:%d\n", Width);
12 printf("屏幕高度:%d\n", Height);*/
13
14 CDC memDC;//内存DC
15 memDC.CreateCompatibleDC(pDC);
16
17 CBitmap memBitmap, *oldmemBitmap;//建立和屏幕兼容的bitmap
18 memBitmap.CreateCompatibleBitmap(pDC, Width, Height);
19
20 oldmemBitmap = memDC.SelectObject(&memBitmap);//将memBitmap选入内存DC
21 memDC.BitBlt(0, 0, Width, Height, pDC, 0, 0, SRCCOPY);//复制屏幕图像到内存DC
22
23 //以下代码保存memDC中的位图到文件
24 BITMAP bmp;
25 memBitmap.GetBitmap(&bmp);//获得位图信息
26
27 errno_t err;
28 FILE *fp;
29 err = fopen_s(&fp,filename, "w+b");
30
31 BITMAPINFOHEADER bih = { 0 };//位图信息头
32 bih.biBitCount = bmp.bmBitsPixel;//每个像素字节大小
33 bih.biCompression = BI_RGB;
34 bih.biHeight = bmp.bmHeight;//高度
35 bih.biPlanes = 1;
36 bih.biSize = sizeof(BITMAPINFOHEADER);
37 bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;//图像数据大小
38 bih.biWidth = bmp.bmWidth;//宽度
39
40 BITMAPFILEHEADER bfh = { 0 };//位图文件头
41 bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位图数据的偏移量
42 bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;//文件总的大小
43 bfh.bfType = (WORD)0x4d42;
44
45 fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);//写入位图文件头
46
47 fwrite(&bih, 1, sizeof(BITMAPINFOHEADER), fp);//写入位图信息头
48
49 byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];//申请内存保存位图数据
50
51 GetDIBits(memDC.m_hDC, (HBITMAP)memBitmap.m_hObject, 0, Height, p,
52 (LPBITMAPINFO)&bih, DIB_RGB_COLORS);//获取位图数据
53
54 fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);//写入位图数据
55
56 delete[] p;
57 p = nullptr;
58
59 fclose(fp);
60
61 memDC.SelectObject(oldmemBitmap);
62 }