#include<d3d9.h>
#include<iostream>
#pragma comment(lib,"d3d9.lib")
using namespace std;
//截取全屏
void CaptureScreen(void *data)
{//1 创建directx3d对象static IDirect3D9 *d3d = nullptr;if (!d3d){d3d = Direct3DCreate9(D3D_SDK_VERSION);}if (!d3d)return;//2 创建显卡设备对象static IDirect3DDevice9 *device = nullptr;if (!device){D3DPRESENT_PARAMETERS pa;ZeroMemory(&pa,sizeof(D3DPRESENT_PARAMETERS));pa.Windowed = true;pa.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;pa.SwapEffect = D3DSWAPEFFECT_DISCARD;pa.hDeviceWindow = GetDesktopWindow();d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, 0,D3DCREATE_HARDWARE_VERTEXPROCESSING, &pa, &device);if (!device)return;}int w = GetSystemMetrics(SM_CXSCREEN);int h = GetSystemMetrics(SM_CYSCREEN);//3 创建离屏表面static IDirect3DSurface9 *sur = nullptr;if (!sur){device->CreateOffscreenPlainSurface(w,h,D3DFMT_A8R8G8B8,//像素格式D3DPOOL_SCRATCH,//存储位置 &sur,0);}if (!sur)return;//4 截取屏幕device->GetFrontBufferData(0,sur);//5 取出数据D3DLOCKED_RECT rect;ZeroMemory(&rect, sizeof(rect));if (sur->LockRect(&rect, 0, 0) != S_OK){return;}memcpy(data, rect.pBits, w * h * 4);sur->UnlockRect();//解锁cout << ".";
}int main()
{FILE *fp = fopen("out.rgb", "wb");int size = 1920 * 1080 * 4;char *buffer = new char[size];for (int i = 0; i < 100; i++){CaptureScreen(buffer);fwrite(buffer,1,size,fp);Sleep(100);}return 0;
}