64,663
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include "windows.h"
using namespace std;
int main(int argc, char* argv[])
{
//获取当前整个屏幕DC
HDC hDC = GetDC(GetDesktopWindow());
//CDC *pDC = CDC::FromHandle(hDC);
//获得颜色模式
int BitPerPixel = GetDeviceCaps(hDC,BITSPIXEL);
int Width = GetDeviceCaps(hDC,HORZRES);
int Height = GetDeviceCaps(hDC,VERTRES);
cout << "当前屏幕色彩模式为" << BitPerPixel << "位色彩" << endl
<< "屏幕宽度:" << Width << endl
<< "屏幕高度:" << Height << endl << endl;
HDC memDC;//内存DC
memDC = CreateCompatibleDC(hDC);
HBITMAP memBitmap;
HGDIOBJ oldmemBitmap;//建立和屏幕兼容的bitmap
memBitmap = CreateCompatibleBitmap(hDC, Width, Height);
oldmemBitmap = SelectObject(memDC, memBitmap);//将memBitmap选入内存DC
BitBlt(memDC, 0, 0, Width, Height, hDC, 0, 0, SRCCOPY);//复制屏幕图像到内存DC
//以下代码保存memDC中的位图到文件
//BITMAP bmp;
//GetBitmap(&bmp);//获得位图信息
BITMAP bm;
GetObject(memBitmap, sizeof(BITMAP), (LPBYTE)&bm);
FILE *fp = fopen("Screen.bmp", "w+b");
BITMAPINFOHEADER bih = {0};//位图信息头
bih.biBitCount = bm.bmBitsPixel;//每个像素字节大小
bih.biCompression = BI_RGB;
bih.biHeight = bm.bmHeight;//高度
bih.biPlanes = 1;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = bm.bmWidthBytes * bm.bmHeight;//图像数据大小
bih.biWidth = bm.bmWidth;//宽度
BITMAPFILEHEADER bfh = {0};//位图文件头
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位图数据的偏移量
bfh.bfSize = bfh.bfOffBits + bm.bmWidthBytes * bm.bmHeight;//文件总的大小
bfh.bfType = (WORD)0x4d42;
fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);//写入位图文件头
fwrite(&bih, 1, sizeof(BITMAPINFOHEADER), fp);//写入位图信息头
byte * p = new byte[bm.bmWidthBytes * bm.bmHeight];//申请内存保存位图数据
GetDIBits(memDC, (HBITMAP)memBitmap, 0, Height, p,
(LPBITMAPINFO) &bih, DIB_RGB_COLORS);//获取位图数据
fwrite(p, 1, bm.bmWidthBytes * bm.bmHeight, fp);//写入位图数据
delete [] p;
fclose(fp);
SelectObject(memDC,oldmemBitmap);
cout << "屏幕图像已存储到文件中" << endl;
return 0;
}
static CDC MemDc,ScrDc,MemDC1;// 屏幕和内存设备描述表
static CDC* pDC;
static CBitmap ScrBmp;
static CClientDC dc(this);
static HDC m_hdcScreen=::GetDC(NULL);
MemDc.CreateCompatibleDC(&ScrDc);//该函数创建一个与指定设备兼容的内存设备上下文环境(DC)。
ScrDc.CreateDC("display",NULL,NULL,NULL);//获取屏幕设备句柄
ScrBmp.CreateCompatibleBitmap(&ScrDc,xx,yy);//获取与ScrDc句柄相关的位图,尺寸为1024*768