DirectX 2d WinForm Setup for SharpDX 2D
See the question and my original answer on StackOverflowYou can't really use SharpDX if you don't know / understand DirectX, DXGI, Direct2D. Also you talk about the "future", but SharpDX is no longer active since 2 years https://github.com/sharpdx/SharpDX.
Your code has two problems:
- you recreate a device (with a swap chain) and use the D2D device context from the first device
- you don't need to specify the properties when creating the bitmap, they are implicit from the underlying DXGI surface
This is a code that should work:
// create D3D device & (DXGI) swap chain
var scd = new SwapChainDescription()
{
BufferCount = 1,
Flags = SwapChainFlags.None,
IsWindowed = true,
ModeDescription = new ModeDescription(panel1.ClientSize.Width, panel1.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
OutputHandle = panel1.Handle, // make sure this is not IntPtr.Zero
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
SharpDX.Direct3D11.Device.CreateWithSwapChain(
DriverType.Hardware,
DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport,
scd,
out device,
out swapChain);
// get swap chain backbuffer
var backBuffer = swapChain.GetBackBuffer<Surface>(0);
// create DXGI & D2D devices context
var dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device2>();
var d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice);
d2dContext = new SharpDX.Direct2D1.DeviceContext(
d2dDevice,
DeviceContextOptions.None);
// create target
d2dTarget = new Bitmap1(d2dContext, backBuffer);