1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| public Device DeviceComputer;
public Texture2DDescription Texture2DDescriptionObject;
public OutputDuplication DuplicatedOutputObject;
public Texture2D Texture2DObject;
public DxScreenCapture()
{
// # of graphics card adapter
const int numAdapter = 0;
// # of output device (i.e. monitor)
const int numOutput = 0;
// Create DXGI Factory1
var factory = new Factory1();
var adapter = factory.GetAdapter1(numAdapter);
// Create device from Adapter
DeviceComputer = new Device(DriverType.Hardware, DeviceCreationFlags.PreventThreadingOptimizations);
// Get DXGI.Output
var output = adapter.GetOutput(numOutput);
var output1 = output.QueryInterface<Output1>();
// Width/Height of desktop to capture
int width = Program.IniFile.Configs["screen_config"].GetInt("width");
int height = Program.IniFile.Configs["screen_config"].GetInt("height");
// Create Staging texture CPU-accessible
Texture2DDescriptionObject = new Texture2DDescription
{
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = width,
Height = height,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
Texture2DObject = new Texture2D(DeviceComputer, Texture2DDescriptionObject);
// Duplicate the output
DuplicatedOutputObject = output1.DuplicateOutput(DeviceComputer);
}
public bool CaptureScreen(out DataStream dataStreamCapture)
{
dataStreamCapture = null;
try
{
SharpDX.DXGI.Resource screenResource;
OutputDuplicateFrameInformation duplicateFrameInformation;
// Try to get duplicated frame within given time
DuplicatedOutputObject.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource);
// copy resource into memory that can be accessed by the CPU
using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
DeviceComputer.ImmediateContext.CopyResource(screenTexture2D, Texture2DObject);
// Get the desktop capture texture
DeviceComputer.ImmediateContext.MapSubresource(Texture2DObject, 0, MapMode.Read, MapFlags.None, out dataStreamCapture);
screenResource.Dispose();
DuplicatedOutputObject.ReleaseFrame();
return true;
}
catch (SharpDXException e)
{
return false;
}
} |
Partager