将Direct2D渲染重定向到WPF控件

Nic*_*ick 12 c# c++ directx wpf direct2d

我正在开发的绘图应用程序Visual C++通过以下方式Direct2D.我有一个演示应用程序,其中:

// create the ID2D1Factory
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pDirect2dFactory);

// create the main window
HWND m_hwnd = CreateWindow(...);

// set the render target of type ID2D1HwndRenderTarget
m_pDirect2dFactory->CreateHwndRenderTarget(
            D2D1::RenderTargetProperties(),
            D2D1::HwndRenderTargetProperties(m_hwnd, size),
            &m_pRenderTarget
            );
Run Code Online (Sandbox Code Playgroud)

当我收到WM_PAINT消息时,我会画出我的形状.

现在我需要开发一个代表我的新渲染目标的WPF控件(一种Panel)(因此它将替换主窗口m_hwnd),这样我就可以创建一个新的(C#)WPF项目,其主窗口具有子窗口我的自定义面板,而渲染部分保留在本机C++/CLI DLL项目中.

我怎样才能做到这一点?我必须设置为新的渲染目标?

我想用我的WPF窗口的句柄:

IntPtr windowHandle = new WindowInteropHelper(MyMainWindow).Handle;
Run Code Online (Sandbox Code Playgroud)

但我需要在我的面板上画画,而不是在我的窗户上.

请注意,我不想将任何WPF类用于渲染部分(Shapes,DrawingVisuals...)

gli*_*ite 3

您必须实现一个托管 Win32 Window 的类m_hwnd。该类继承自HwndHost

此外,您必须重写HwndHost.BuildWindowCoreHwndHost.DestroyWindowCore方法:

HandleRef BuildWindowCore(HandleRef hwndParent) 
{
  HWND parent = reinterpret_cast<HWND>(hwndParent.Handle.ToPointer());

  // here create your Window and set in the CreateWindow function
  // its parent by passing the parent variable defined above
  m_hwnd = CreateWindow(..., 
                        parent, 
                        ...);

  return HandleRef(this, IntPtr(m_hwnd));
}


void DestroyWindowCore(HandleRef hwnd) 
{
  DestroyWindow(m_hwnd);  // hwnd.Handle
}
Run Code Online (Sandbox Code Playgroud)

请遵循本教程:演练:在 WPF 中托管 Win32 控件