Skip to content

Rendering to Windows::Forms and WPF

ZieIony edited this page Jan 9, 2019 · 2 revisions

Using DirectX to render images in a Windows::Forms-based application is very easy. Windows::Forms is a wrapper over WinAPI, so the basics are the same as when rendering to a native window. Each Control has a Handle property, which exposes underlying HWND of the window and OnPaint corresponds to WinAPI's WM_PAINT event. It means that you can just init DirectX with that HWND Handle and draw in OnPaint.

HWND hwnd = (HWND)control.Handle;
graphics.Factory->CreateSwapChainForHwnd(
    queue, hwnd, &swapChainDesc, nullptr, nullptr, &swapChain1);

In WPF and UWP it's more difficult, because these frameworks don't use windows in WinAPI's understanding, but draw everything manually in one window. The easiest approach in such a case is to use the control called WindowsFormsHost to wrap a Windows::Forms control in a WPF project. Then the solution is identical to the above one.

https://github.com/ZieIony/Ghurund/blob/master/ManagedDll/SurfaceView.cs

This is the Windows::Forms control I wrote for the purpose of rendering from native code to a managed window. You can see OnPaint method used to draw. My Window class manages HWND for DirectX.

Clone this wiki locally