Reputation: 1
I used directx11 in c# to take a screenshot, but in the end I only got 0 in span, I don't know why, there is no error in the middle and the execution returns 0, the code uses the silk.net.direct3d11 library
I also tried this by creating an intermediate Texture2D, then copying my desktopTexture to this intermediate Texture2D, and then copying from the intermediate Texture2D to 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);
What am i doing wrong?
Upvotes: -2
Views: 143
Reputation: 69724
AcquireNextFrame
has no promise to give you a screenshot right away. You might need to call it a few times before the texture is ready.
See more in this answer: AcquireNextFrame not working (Desktop Duplication API & D3D11).
Upvotes: 0