Sending event messages from C# D3DImage to C++ Direct3D window

If you’re integrating a C++ Direct3D HWND into WPF via D3DImage, and you were handling a lot of messages in your C++ WndProc, then fear not as you will not have to implement each WPF event individually and translate them to a Win32 event. Instead, you can add a hook to a C# WndProc that will live alongside other WPF events.

using System;
using System.Windows;
using System.Windows.Interop;

namespace WpfApplication1
    public partial class Window1 : Window
        private D3DImage d3dImage;

        public Window1()
            // Initialize d3dImage scene, frontbufferavailable, etc

        // ...

        protected override void OnSourceInitialized(EventArgs e)
            HwndSource source = PresentationSource.FromVisual(this) as HwndSource;

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
            // Send message to C++ via P/Invoke
            PInvokeSendMessage((UIntPtr)msg, wParam, lParam);

            return IntPtr.Zero;

The beauty is that you will still be able to override every other WPF event (such as PreviewKeyDown, KeyDown, etc) as well. The order that they will be called is as follows: PreviewKeyDown -> KeyDown -> WndProc (WM_KEYDOWN). Therefore it’s possible to make decisions in the regular WPF events to decide whether the event should be sent to your Direct3D engine in C++. As you might not want to send mouse events when the focus isn’t directly on your D3DImage.

Remove the hook when the Window is Closing.

  • Dave

    good work