C++使用DXGI截图代码
时间: 2024-04-30 18:23:33 浏览: 307
DXGI急速截屏代码,亲测非常好用
3星 · 编辑精心推荐
以下是使用DXGI截图的示例代码:
```cpp
#include <d3d11.h>
#include <dxgi1_2.h>
#include <iostream>
int main()
{
HRESULT hr = S_OK;
// 创建DXGI设备
IDXGIFactory2* pFactory = nullptr;
hr = CreateDXGIFactory2(0, IID_PPV_ARGS(&pFactory));
if (FAILED(hr))
{
std::cout << "Failed to create DXGI factory." << std::endl;
return 1;
}
// 枚举第一个适配器
IDXGIAdapter1* pAdapter = nullptr;
hr = pFactory->EnumAdapters1(0, &pAdapter);
if (FAILED(hr))
{
std::cout << "Failed to enumerate adapters." << std::endl;
return 1;
}
// 创建D3D11设备和设备上下文
ID3D11Device* pDevice = nullptr;
ID3D11DeviceContext* pContext = nullptr;
hr = D3D11CreateDevice(pAdapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, nullptr, 0,
D3D11_SDK_VERSION, &pDevice, nullptr, &pContext);
if (FAILED(hr))
{
std::cout << "Failed to create D3D11 device and context." << std::endl;
return 1;
}
// 获取DXGI设备
IDXGIDevice1* pDXGIDevice = nullptr;
hr = pDevice->QueryInterface(__uuidof(IDXGIDevice1), (void**)&pDXGIDevice);
if (FAILED(hr))
{
std::cout << "Failed to get DXGI device." << std::endl;
return 1;
}
// 获取DXGI适配器
IDXGIAdapter* pDXGIAdapter = nullptr;
hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&pDXGIAdapter);
if (FAILED(hr))
{
std::cout << "Failed to get DXGI adapter." << std::endl;
return 1;
}
// 获取DXGI工厂
IDXGIFactory* pDXGIFactory = nullptr;
hr = pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&pDXGIFactory);
if (FAILED(hr))
{
std::cout << "Failed to get DXGI factory." << std::endl;
return 1;
}
// 获取前缓冲表面
IDXGISurface* pBackBufferSurface = nullptr;
hr = pDXGIFactory->CreateSwapChain(pDXGIDevice, &swapChainDesc, &pSwapChain);
if (FAILED(hr))
{
std::cout << "Failed to create swap chain." << std::endl;
return 1;
}
hr = pSwapChain->GetBuffer(0, __uuidof(IDXGISurface), (void**)&pBackBufferSurface);
if (FAILED(hr))
{
std::cout << "Failed to get back buffer surface." << std::endl;
return 1;
}
// 保存图像到文件
hr = SaveSurfaceToFile(pBackBufferSurface, L"Screenshot.png");
if (FAILED(hr))
{
std::cout << "Failed to save screenshot to file." << std::endl;
return 1;
}
// 释放资源
pBackBufferSurface->Release();
pSwapChain->Release();
pDXGIFactory->Release();
pDXGIAdapter->Release();
pDXGIDevice->Release();
pContext->Release();
pDevice->Release();
pAdapter->Release();
pFactory->Release();
return 0;
}
```
在此示例中,我们首先使用`CreateDXGIFactory2`函数创建了一个DXGI工厂对象。然后,我们使用`EnumAdapters1`函数枚举第一个适配器,并使用`D3D11CreateDevice`函数创建了一个D3D11设备和设备上下文对象。接下来,我们使用`QueryInterface`函数获取了设备对象的`IDXGIDevice1`接口,然后使用`GetParent`函数获取了适配器对象的`IDXGIAdapter`接口,最后使用`GetParent`函数获取了工厂对象的`IDXGIFactory`接口。
然后,我们使用`CreateSwapChain`函数创建了一个交换链对象,并使用`GetBuffer`函数获取了前缓冲表面对象。最后,我们使用`SaveSurfaceToFile`函数将表面对象保存为PNG图像文件。
请注意,此示例中省略了一些错误检查和释放资源的代码。在实际应用中,应该对所有函数调用返回值进行错误检查,并在程序结束时释放所有资源。
阅读全文