Directx9 screenshot

  • Tags : ffmpeg c++
  • time :

1. Directx9 screenshot interface

  1. Direct3DCreate9 Creating Directx3D Objects
  2. Create Device: Create a graphics card device object
  3. Create Off screen PlainSurface: Create an off screen surface (a piece of storage space)
  4. GetFrontBufferData: Front Surface

LockRect function (taking the content of the surface)

  1. D3DLOCKED_ RECT lr;
  2. ZeroMemory (& lr, sizeof (D3DLOCKED RECT));
  3. PSurface -> LockRect (&lr, NULL, 0)
  4. DEORD * pBuf= (DWORD *) lr PBits;
  5. PSurface -> UnlockRect();
#include <d3d9.h>
#pragma comment(lib,"d3d9.lib")
#pragma warning (disable:4996)
#include <iostream>
using namespace std;
//capture full screen 
void CaptureScreen(void* data)
{
	//1. create direct3d object 
	static IDirect3D9* d3d = NULL;
	if (!d3d)
	{
		d3d = Direct3DCreate9(D3D_SDK_VERSION);
	}
	if (!d3d)
		return;
	//2. create device to object graphics cards 
	static IDirect3DDevice9* device = NULL;
	if (!device)
	{
		D3DPRESENT_PARAMETERS pa;
		ZeroMemory(&pa, sizeof(pa));
		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;
	
	//3. create off screen surfaces 
	//obtain the width and height of the screen 
	int w = GetSystemMetrics(SM_CXSCREEN);
	int h = GetSystemMetrics(SM_CYSCREEN);
	static IDirect3DSurface9* sur = NULL;
	if (!sur)
	{
		device->CreateOffscreenPlainSurface(w, h,
			D3DFMT_A8B8G8R8,		//corresponding pixel format 
			D3DPOOL_SCRATCH,		//storage location 
			&sur, 0);				//save parameters in sur
	}
	if (!sur)
		return;
	//capture the current screen displayed on the graphics card 
	device->GetFrontBufferData(0, sur);
	//retrieve data 
	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();//unlock 
}
int main()
{ 
	char* buf = new char[1920 * 1080 * 4];
	FILE* fp = fopen("./file/out.reb", "wb");
	int size = 1920 * 1080 * 4;
	for (int i = 0; i < 100; i++)
	{
		CaptureScreen(buf);
		fwrite(buf, 1, size, fp);
		Sleep(100);
	}
	return 0;
}