我在c#中使用directx11进行截图,但是最终我在span中只得到0,不知道为什么,中间没有错误并且执行返回0,代码使用silk.net. direct3d11 库
我还尝试过创建一个中间Texture2D,然后将我的desktopTexture复制到这个中间Texture2D,然后从中间Texture2D复制到stagingResource
//....
ID3D11Device* device=null;
ID3D11DeviceContext* context=null;
D3DFeatureLevel featureLevel=D3DFeatureLevel.Level101;
D3DFeatureLevel[] featureLevels =
[
D3DFeatureLevel.Level111, D3DFeatureLevel.Level110, D3DFeatureLevel.Level101,D3DFeatureLevel.Level100
];
fixed (D3DFeatureLevel* pFeatureLevels = &featureLevels[0])
{
D3D11 d3D11 = new D3D11(new DefaultNativeContext("d3d11"));
if (d3D11.CreateDevice((IDXGIAdapter*)adapter1, D3DDriverType.Unknown, IntPtr.Zero,
(uint)CreateDeviceFlag.None,pFeatureLevels,(uint)featureLevels.Length, D3D11.SdkVersion, ref device,
&featureLevel, ref context)!=0){/*..*/}
}
ID3D11DeviceContext* immediateContext = null;
device->GetImmediateContext(ref immediateContext);
IDXGIOutputDuplication *outputDuplication = null;
if (output5.DuplicateOutput((IUnknown*)device, ref outputDuplication)!=0){/*..*/}
OutduplFrameInfo outduplFrameInfo = new OutduplFrameInfo();
IDXGIResource* desktopResource = null;
if (outputDuplication->AcquireNextFrame(1000, &outduplFrameInfo, &desktopResource)!=0{/*..*/}
if (desktopResource->QueryInterface<ID3D11Resource>(out var desktopTexture)!=0){/*..*/}
Texture2DDesc stagingTextureDesc = new()
{
CPUAccessFlags = (uint)CpuAccessFlag.Read,
BindFlags = (uint)(BindFlag.None),
Format = Format.FormatB8G8R8A8Unorm,
Width = (uint)desc.DesktopCoordinates.Size.X,
Height = (uint)desc.DesktopCoordinates.Size.Y,
MiscFlags = (uint)ResourceMiscFlag.None,
MipLevels = 1,
ArraySize = 1,
SampleDesc = { Count = 1, Quality = 0 },
Usage = Usage.Staging
};
ID3D11Texture2D* stagingTexture = null;
if (device->CreateTexture2D(&stagingTextureDesc,null,ref stagingTexture )!=0){/*..*/}
stagingTexture->QueryInterface<ID3D11Resource>(out var stagingResource);
immediateContext->CopyResource(stagingResource, desktopTexture);
MappedSubresource mappedSubresource=new MappedSubresource();
if (immediateContext->Map(stagingResource, 0, Map.Read, 0, &mappedSubresource)!=0){/*..*/}
var span = new ReadOnlySpan<byte>(mappedSubresource.PData,
(int)mappedSubresource.DepthPitch);
我做错了什么?
AcquireNextFrame
不承诺立即给您截图。在纹理准备好之前,您可能需要调用它几次。
在此答案中查看更多内容:AcquireNextFrame 不起作用(桌面复制 API 和 D3D11)。