Răsfoiți Sursa

Merge pull request #30 from DigitalRune/wpfinterop

Added WpfInteropSample which shows how to render into a WPF D3DImage.
Dominique Louis 12 ani în urmă
părinte
comite
83b56cf464

+ 8 - 0
WpfInteropSample/App.xaml

@@ -0,0 +1,8 @@
+<Application x:Class="WpfInteropSample.App"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             StartupUri="MainWindow.xaml">
+    <Application.Resources>
+         
+    </Application.Resources>
+</Application>

+ 6 - 0
WpfInteropSample/App.xaml.cs

@@ -0,0 +1,6 @@
+namespace WpfInteropSample
+{
+    public partial class App
+    {
+    }
+}

+ 446 - 0
WpfInteropSample/D3D11Host.cs

@@ -0,0 +1,446 @@
+using System;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using Microsoft.Xna.Framework;
+using Microsoft.Xna.Framework.Graphics;
+using Color = Microsoft.Xna.Framework.Color;
+using Matrix = Microsoft.Xna.Framework.Matrix;
+
+
+namespace WpfInteropSample
+{
+    /// <summary>
+    /// Host a Direct3D 11 scene.
+    /// </summary>
+    public class D3D11Host : Image
+    {
+        #region Fields
+        // The Direct3D 11 device (shared by all D3D11Host elements):
+        private static GraphicsDevice _graphicsDevice;
+        private static int _referenceCount;
+        private static readonly object _graphicsDeviceLock = new object();
+
+        // Image source:
+        private RenderTarget2D _renderTarget;
+        private D3D11Image _d3D11Image;
+        private bool _resetBackBuffer;
+
+        // Render timing:
+        private readonly Stopwatch _timer;
+        private TimeSpan _lastRenderingTime;
+        #endregion
+
+        #region Properties
+        /// <summary>
+        /// Gets a value indicating whether the controls runs in the context of a designer (e.g.
+        /// Visual Studio Designer or Expression Blend).
+        /// </summary>
+        /// <value>
+        /// <see langword="true" /> if controls run in design mode; otherwise, 
+        /// <see langword="false" />.
+        /// </value>
+        public static bool IsInDesignMode
+        {
+            get
+            {
+                if (!_isInDesignMode.HasValue)
+                    _isInDesignMode = (bool)DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof(FrameworkElement)).Metadata.DefaultValue;
+
+                return _isInDesignMode.Value;
+            }
+        }
+        private static bool? _isInDesignMode;
+
+
+        /// <summary>
+        /// Gets the graphics device.
+        /// </summary>
+        /// <value>The graphics device.</value>
+        public GraphicsDevice GraphicsDevice
+        {
+            get { return _graphicsDevice; }
+        }
+        #endregion
+
+
+        #region Constructors
+        /// <summary>
+        /// Initializes a new instance of the <see cref="D3D11Host"/> class.
+        /// </summary>
+        public D3D11Host()
+        {
+            _timer = new Stopwatch();
+            Loaded += OnLoaded;
+            Unloaded += OnUnloaded;
+        }
+        #endregion
+
+
+        #region Methods
+        private void OnLoaded(object sender, RoutedEventArgs eventArgs)
+        {
+            if (IsInDesignMode)
+                return;
+
+            InitializeGraphicsDevice();
+            InitializeImageSource();
+            Initialize();
+            StartRendering();
+        }
+
+
+        private void OnUnloaded(object sender, RoutedEventArgs eventArgs)
+        {
+            if (IsInDesignMode)
+                return;
+
+            StopRendering();
+            Unitialize();
+            UnitializeImageSource();
+            UninitializeGraphicsDevice();
+        }
+
+
+        private static void InitializeGraphicsDevice()
+        {
+            lock (_graphicsDeviceLock)
+            {
+                _referenceCount++;
+                if (_referenceCount == 1)
+                {
+                    // Create Direct3D 11 device.
+                    var presentationParameters = new PresentationParameters
+                    {
+                        // Do not associate graphics device with window.
+                        DeviceWindowHandle = IntPtr.Zero,
+                    };
+                    _graphicsDevice = new GraphicsDevice(GraphicsProfile.HiDef, presentationParameters);
+                }
+            }
+        }
+
+
+        private static void UninitializeGraphicsDevice()
+        {
+            lock (_graphicsDeviceLock)
+            {
+                _referenceCount--;
+                if (_referenceCount == 0)
+                {
+                    _graphicsDevice.Dispose();
+                    _graphicsDevice = null;
+                }
+            }
+        }
+
+
+        private void InitializeImageSource()
+        {
+            _d3D11Image = new D3D11Image();
+            _d3D11Image.IsFrontBufferAvailableChanged += OnIsFrontBufferAvailableChanged;
+            CreateBackBuffer();
+            Source = _d3D11Image;
+        }
+
+
+        private void UnitializeImageSource()
+        {
+            _d3D11Image.IsFrontBufferAvailableChanged -= OnIsFrontBufferAvailableChanged;
+            Source = null;
+
+            if (_d3D11Image != null)
+            {
+                _d3D11Image.Dispose();
+                _d3D11Image = null;
+            }
+            if (_renderTarget != null)
+            {
+                _renderTarget.Dispose();
+                _renderTarget = null;
+            }
+        }
+
+
+        private void CreateBackBuffer()
+        {
+            _d3D11Image.SetBackBuffer(null);
+            if (_renderTarget != null)
+            {
+                _renderTarget.Dispose();
+                _renderTarget = null;
+            }
+
+            int width = Math.Max((int)ActualWidth, 1);
+            int height = Math.Max((int)ActualHeight, 1);
+            _renderTarget = new RenderTarget2D(_graphicsDevice, width, height, false, SurfaceFormat.Bgr32, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents, true);
+            _d3D11Image.SetBackBuffer(_renderTarget);
+        }
+
+
+        private void StartRendering()
+        {
+            if (_timer.IsRunning)
+                return;
+
+            CompositionTarget.Rendering += OnRendering;
+            _timer.Start();
+        }
+
+
+        private void StopRendering()
+        {
+            if (!_timer.IsRunning)
+                return;
+
+            CompositionTarget.Rendering -= OnRendering;
+            _timer.Stop();
+        }
+
+
+        private void OnRendering(object sender, EventArgs eventArgs)
+        {
+            if (!_timer.IsRunning)
+                return;
+
+            // Recreate back buffer if necessary.
+            if (_resetBackBuffer)
+                CreateBackBuffer();
+
+            // CompositionTarget.Rendering event may be raised multiple times per frame
+            // (e.g. during window resizing).
+            var renderingEventArgs = (RenderingEventArgs)eventArgs;
+            if (_lastRenderingTime != renderingEventArgs.RenderingTime || _resetBackBuffer)
+            {
+                _lastRenderingTime = renderingEventArgs.RenderingTime;
+
+                GraphicsDevice.SetRenderTarget(_renderTarget);
+                Render(_timer.Elapsed);
+                GraphicsDevice.Flush();
+            }
+
+            _d3D11Image.Invalidate(); // Always invalidate D3DImage to reduce flickering
+                                      // during window resizing.
+
+            _resetBackBuffer = false;
+        }
+
+
+        /// <summary>
+        /// Raises the <see cref="FrameworkElement.SizeChanged" /> event, using the specified 
+        /// information as part of the eventual event data.
+        /// </summary>
+        /// <param name="sizeInfo">Details of the old and new size involved in the change.</param>
+        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
+        {
+            _resetBackBuffer = true;
+            base.OnRenderSizeChanged(sizeInfo);
+        }
+
+
+        private void OnIsFrontBufferAvailableChanged(object sender, DependencyPropertyChangedEventArgs eventArgs)
+        {
+            if (_d3D11Image.IsFrontBufferAvailable)
+            {
+                StartRendering();
+                _resetBackBuffer = true;
+            }
+            else
+            {
+                StopRendering();
+            }
+        }
+
+
+        #region ----- Example Scene -----
+
+        // Source: http://msdn.microsoft.com/en-us/library/bb203926(v=xnagamestudio.40).aspx
+
+        // Note: This is just an example. To improve the D3D11Host make the methods 
+        // Initialize(), Unitialize(), and Render() protected virtual or call an 
+        // external "renderer".
+
+        Matrix _worldMatrix;
+        Matrix _viewMatrix;
+        Matrix _projectionMatrix;
+        VertexDeclaration vertexDeclaration;
+        VertexBuffer _vertexBuffer;
+        BasicEffect _basicEffect;
+
+
+        private void Initialize()
+        {
+            float tilt = MathHelper.ToRadians(0);  // 0 degree angle
+            // Use the world matrix to tilt the cube along x and y axes.
+            _worldMatrix = Matrix.CreateRotationX(tilt) * Matrix.CreateRotationY(tilt);
+            _viewMatrix = Matrix.CreateLookAt(new Vector3(5, 5, 5), Vector3.Zero, Vector3.Up);
+
+            _projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
+                MathHelper.ToRadians(45),  // 45 degree angle
+                (float)GraphicsDevice.Viewport.Width /
+                (float)GraphicsDevice.Viewport.Height,
+                1.0f, 100.0f);
+
+            _basicEffect = new BasicEffect(GraphicsDevice);
+
+            _basicEffect.World = _worldMatrix;
+            _basicEffect.View = _viewMatrix;
+            _basicEffect.Projection = _projectionMatrix;
+
+            // primitive color
+            _basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
+            _basicEffect.DiffuseColor = new Vector3(1.0f, 1.0f, 1.0f);
+            _basicEffect.SpecularColor = new Vector3(0.25f, 0.25f, 0.25f);
+            _basicEffect.SpecularPower = 5.0f;
+            _basicEffect.Alpha = 1.0f;
+
+            _basicEffect.LightingEnabled = true;
+            if (_basicEffect.LightingEnabled)
+            {
+                _basicEffect.DirectionalLight0.Enabled = true; // enable each light individually
+                if (_basicEffect.DirectionalLight0.Enabled)
+                {
+                    // x direction
+                    _basicEffect.DirectionalLight0.DiffuseColor = new Vector3(1, 0, 0); // range is 0 to 1
+                    _basicEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(-1, 0, 0));
+                    // points from the light to the origin of the scene
+                    _basicEffect.DirectionalLight0.SpecularColor = Vector3.One;
+                }
+
+                _basicEffect.DirectionalLight1.Enabled = true;
+                if (_basicEffect.DirectionalLight1.Enabled)
+                {
+                    // y direction
+                    _basicEffect.DirectionalLight1.DiffuseColor = new Vector3(0, 0.75f, 0);
+                    _basicEffect.DirectionalLight1.Direction = Vector3.Normalize(new Vector3(0, -1, 0));
+                    _basicEffect.DirectionalLight1.SpecularColor = Vector3.One;
+                }
+
+                _basicEffect.DirectionalLight2.Enabled = true;
+                if (_basicEffect.DirectionalLight2.Enabled)
+                {
+                    // z direction
+                    _basicEffect.DirectionalLight2.DiffuseColor = new Vector3(0, 0, 0.5f);
+                    _basicEffect.DirectionalLight2.Direction = Vector3.Normalize(new Vector3(0, 0, -1));
+                    _basicEffect.DirectionalLight2.SpecularColor = Vector3.One;
+                }
+            }
+
+            vertexDeclaration = new VertexDeclaration(new[]
+            {
+                new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
+                new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
+                new VertexElement(24, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0)
+            });
+
+            Vector3 topLeftFront = new Vector3(-1.0f, 1.0f, 1.0f);
+            Vector3 bottomLeftFront = new Vector3(-1.0f, -1.0f, 1.0f);
+            Vector3 topRightFront = new Vector3(1.0f, 1.0f, 1.0f);
+            Vector3 bottomRightFront = new Vector3(1.0f, -1.0f, 1.0f);
+            Vector3 topLeftBack = new Vector3(-1.0f, 1.0f, -1.0f);
+            Vector3 topRightBack = new Vector3(1.0f, 1.0f, -1.0f);
+            Vector3 bottomLeftBack = new Vector3(-1.0f, -1.0f, -1.0f);
+            Vector3 bottomRightBack = new Vector3(1.0f, -1.0f, -1.0f);
+
+            Vector2 textureTopLeft = new Vector2(0.0f, 0.0f);
+            Vector2 textureTopRight = new Vector2(1.0f, 0.0f);
+            Vector2 textureBottomLeft = new Vector2(0.0f, 1.0f);
+            Vector2 textureBottomRight = new Vector2(1.0f, 1.0f);
+
+            Vector3 frontNormal = new Vector3(0.0f, 0.0f, 1.0f);
+            Vector3 backNormal = new Vector3(0.0f, 0.0f, -1.0f);
+            Vector3 topNormal = new Vector3(0.0f, 1.0f, 0.0f);
+            Vector3 bottomNormal = new Vector3(0.0f, -1.0f, 0.0f);
+            Vector3 leftNormal = new Vector3(-1.0f, 0.0f, 0.0f);
+            Vector3 rightNormal = new Vector3(1.0f, 0.0f, 0.0f);
+
+            var cubeVertices = new VertexPositionNormalTexture[36];
+
+            // Front face.
+            cubeVertices[0] = new VertexPositionNormalTexture(topLeftFront, frontNormal, textureTopLeft);
+            cubeVertices[1] = new VertexPositionNormalTexture(bottomLeftFront, frontNormal, textureBottomLeft);
+            cubeVertices[2] = new VertexPositionNormalTexture(topRightFront, frontNormal, textureTopRight);
+            cubeVertices[3] = new VertexPositionNormalTexture(bottomLeftFront, frontNormal, textureBottomLeft);
+            cubeVertices[4] = new VertexPositionNormalTexture(bottomRightFront, frontNormal, textureBottomRight);
+            cubeVertices[5] = new VertexPositionNormalTexture(topRightFront, frontNormal, textureTopRight);
+
+            // Back face.
+            cubeVertices[6] = new VertexPositionNormalTexture(topLeftBack, backNormal, textureTopRight);
+            cubeVertices[7] = new VertexPositionNormalTexture(topRightBack, backNormal, textureTopLeft);
+            cubeVertices[8] = new VertexPositionNormalTexture(bottomLeftBack, backNormal, textureBottomRight);
+            cubeVertices[9] = new VertexPositionNormalTexture(bottomLeftBack, backNormal, textureBottomRight);
+            cubeVertices[10] = new VertexPositionNormalTexture(topRightBack, backNormal, textureTopLeft);
+            cubeVertices[11] = new VertexPositionNormalTexture(bottomRightBack, backNormal, textureBottomLeft);
+
+            // Top face.
+            cubeVertices[12] = new VertexPositionNormalTexture(topLeftFront, topNormal, textureBottomLeft);
+            cubeVertices[13] = new VertexPositionNormalTexture(topRightBack, topNormal, textureTopRight);
+            cubeVertices[14] = new VertexPositionNormalTexture(topLeftBack, topNormal, textureTopLeft);
+            cubeVertices[15] = new VertexPositionNormalTexture(topLeftFront, topNormal, textureBottomLeft);
+            cubeVertices[16] = new VertexPositionNormalTexture(topRightFront, topNormal, textureBottomRight);
+            cubeVertices[17] = new VertexPositionNormalTexture(topRightBack, topNormal, textureTopRight);
+
+            // Bottom face. 
+            cubeVertices[18] = new VertexPositionNormalTexture(bottomLeftFront, bottomNormal, textureTopLeft);
+            cubeVertices[19] = new VertexPositionNormalTexture(bottomLeftBack, bottomNormal, textureBottomLeft);
+            cubeVertices[20] = new VertexPositionNormalTexture(bottomRightBack, bottomNormal, textureBottomRight);
+            cubeVertices[21] = new VertexPositionNormalTexture(bottomLeftFront, bottomNormal, textureTopLeft);
+            cubeVertices[22] = new VertexPositionNormalTexture(bottomRightBack, bottomNormal, textureBottomRight);
+            cubeVertices[23] = new VertexPositionNormalTexture(bottomRightFront, bottomNormal, textureTopRight);
+
+            // Left face.
+            cubeVertices[24] = new VertexPositionNormalTexture(topLeftFront, leftNormal, textureTopRight);
+            cubeVertices[25] = new VertexPositionNormalTexture(bottomLeftBack, leftNormal, textureBottomLeft);
+            cubeVertices[26] = new VertexPositionNormalTexture(bottomLeftFront, leftNormal, textureBottomRight);
+            cubeVertices[27] = new VertexPositionNormalTexture(topLeftBack, leftNormal, textureTopLeft);
+            cubeVertices[28] = new VertexPositionNormalTexture(bottomLeftBack, leftNormal, textureBottomLeft);
+            cubeVertices[29] = new VertexPositionNormalTexture(topLeftFront, leftNormal, textureTopRight);
+
+            // Right face. 
+            cubeVertices[30] = new VertexPositionNormalTexture(topRightFront, rightNormal, textureTopLeft);
+            cubeVertices[31] = new VertexPositionNormalTexture(bottomRightFront, rightNormal, textureBottomLeft);
+            cubeVertices[32] = new VertexPositionNormalTexture(bottomRightBack, rightNormal, textureBottomRight);
+            cubeVertices[33] = new VertexPositionNormalTexture(topRightBack, rightNormal, textureTopRight);
+            cubeVertices[34] = new VertexPositionNormalTexture(topRightFront, rightNormal, textureTopLeft);
+            cubeVertices[35] = new VertexPositionNormalTexture(bottomRightBack, rightNormal, textureBottomRight);
+
+            _vertexBuffer = new VertexBuffer(GraphicsDevice, vertexDeclaration, cubeVertices.Length, BufferUsage.None);
+            _vertexBuffer.SetData(cubeVertices);
+        }
+
+
+        private void Unitialize()
+        {
+            _vertexBuffer.Dispose();
+            _vertexBuffer = null;
+
+            vertexDeclaration.Dispose();
+            vertexDeclaration = null;
+
+            _basicEffect.Dispose();
+            _basicEffect = null;
+        }
+
+
+        private void Render(TimeSpan time)
+        {
+            GraphicsDevice.Clear(Color.SteelBlue);
+            GraphicsDevice.RasterizerState = RasterizerState.CullNone;
+            GraphicsDevice.SetVertexBuffer(_vertexBuffer);
+
+            // Rotate cube around up-axis.
+            _basicEffect.World = Matrix.CreateRotationY((float)time.Milliseconds / 1000 * MathHelper.TwoPi) * _worldMatrix;
+
+            foreach (var pass in _basicEffect.CurrentTechnique.Passes)
+            {
+                pass.Apply();
+                GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);
+            }
+        }
+        #endregion
+        
+        #endregion
+    }
+}

+ 190 - 0
WpfInteropSample/D3D11Image.cs

@@ -0,0 +1,190 @@
+using System;
+using System.Windows;
+using System.Windows.Interop;
+using Microsoft.Xna.Framework.Graphics;
+using SharpDX.Direct3D9;
+using Texture = SharpDX.Direct3D9.Texture;
+
+
+namespace WpfInteropSample
+{
+    /// <summary>
+    /// Wraps the <see cref="D3DImage"/> to make it compatible with Direct3D 11.
+    /// </summary>
+    /// <remarks>
+    /// The <see cref="D3D11Image"/> should be disposed if no longer needed!
+    /// </remarks>
+    internal class D3D11Image : D3DImage, IDisposable
+    {
+        #region Fields
+        // Use a Direct3D 9 device for interoperability. The device is shared by 
+        // all D3D11Images.
+        private static D3D9 _d3D9;
+        private static int _referenceCount;
+        private static readonly object _d3d9Lock = new object();
+
+        private bool _disposed;
+        private Texture _backBuffer;
+        #endregion
+
+
+        #region Creation & Cleanup
+        /// <summary>
+        /// Initializes a new instance of the <see cref="D3D11Image"/> class.
+        /// </summary>
+        public D3D11Image()
+        {
+            InitializeD3D9();
+        }
+
+
+        /// <summary>
+        /// Releases unmanaged resources before an instance of the <see cref="D3D11Image"/> class is 
+        /// reclaimed by garbage collection.
+        /// </summary>
+        /// <remarks>
+        /// This method releases unmanaged resources by calling the virtual <see cref="Dispose(bool)"/> 
+        /// method, passing in <see langword="false"/>.
+        /// </remarks>
+        ~D3D11Image()
+        {
+            Dispose(false);
+        }
+
+
+        /// <summary>
+        /// Releases all resources used by an instance of the <see cref="D3D11Image"/> class.
+        /// </summary>
+        /// <remarks>
+        /// This method calls the virtual <see cref="Dispose(bool)"/> method, passing in 
+        /// <see langword="true"/>, and then suppresses finalization of the instance.
+        /// </remarks>
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+
+        /// <summary>
+        /// Releases the unmanaged resources used by an instance of the <see cref="D3D11Image"/> class 
+        /// and optionally releases the managed resources.
+        /// </summary>
+        /// <param name="disposing">
+        /// <see langword="true"/> to release both managed and unmanaged resources; 
+        /// <see langword="false"/> to release only unmanaged resources.
+        /// </param>
+        protected virtual void Dispose(bool disposing)
+        {
+            if (!_disposed)
+            {
+                if (disposing)
+                {
+                    // Dispose managed resources.
+                    SetBackBuffer(null);
+                    if (_backBuffer != null)
+                    {
+                        _backBuffer.Dispose();
+                        _backBuffer = null;
+                    }
+                }
+
+                // Release unmanaged resources.
+                UninitializeD3D9();
+                _disposed = true;
+            }
+        }
+        #endregion
+
+
+        #region Methods
+        /// <summary>
+        /// Initializes the Direct3D 9 device.
+        /// </summary>
+        private static void InitializeD3D9()
+        {
+            lock (_d3d9Lock)
+            {
+                _referenceCount++;
+                if (_referenceCount == 1)
+                    _d3D9 = new D3D9();
+            }
+        }
+
+
+        /// <summary>
+        /// Un-initializes the Direct3D 9 device, if no longer needed.
+        /// </summary>
+        private static void UninitializeD3D9()
+        {
+            lock (_d3d9Lock)
+            {
+                _referenceCount--;
+                if (_referenceCount == 0)
+                {
+                    _d3D9.Dispose();
+                    _d3D9 = null;
+                }
+            }
+        }
+
+
+        private void ThrowIfDisposed()
+        {
+            if (_disposed)
+                throw new ObjectDisposedException(GetType().FullName);
+        }
+
+
+        /// <summary>
+        /// Invalidates the front buffer. (Needs to be called when the back buffer has changed.)
+        /// </summary>
+        public void Invalidate()
+        {
+            ThrowIfDisposed();
+
+            if (_backBuffer != null)
+            {
+                Lock();
+                AddDirtyRect(new Int32Rect(0, 0, PixelWidth, PixelHeight));
+                Unlock();
+            }
+        }
+
+
+        /// <summary>
+        /// Sets the back buffer of the <see cref="D3D11Image"/>.
+        /// </summary>
+        /// <param name="texture">The Direct3D 11 texture to be used as the back buffer.</param>
+        public void SetBackBuffer(Texture2D texture)
+        {
+            ThrowIfDisposed();
+
+            var previousBackBuffer = _backBuffer;
+
+            // Create shared texture on Direct3D 9 device.
+            _backBuffer = _d3D9.GetSharedTexture(texture);
+            if (_backBuffer != null)
+            {
+                // Set texture as new back buffer.
+                using (Surface surface = _backBuffer.GetSurfaceLevel(0))
+                {
+                    Lock();
+                    SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
+                    Unlock();
+                }
+            }
+            else
+            {
+                // Reset back buffer.
+                Lock();
+                SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
+                Unlock();                
+            }
+
+            if (previousBackBuffer != null)
+                previousBackBuffer.Dispose();
+        }
+        #endregion
+    }
+}

+ 178 - 0
WpfInteropSample/D3D9.cs

@@ -0,0 +1,178 @@
+using System;
+using System.Runtime.InteropServices;
+using Microsoft.Xna.Framework.Graphics;
+using SharpDX.Direct3D9;
+using DeviceType = SharpDX.Direct3D9.DeviceType;
+using PresentInterval = SharpDX.Direct3D9.PresentInterval;
+using Texture = SharpDX.Direct3D9.Texture;
+
+
+namespace WpfInteropSample
+{
+    /// <summary>
+    /// Represents a Direct3D 9 device required for Direct3D 11 interoperability.
+    /// </summary>
+    /// <remarks>
+    /// It is not possible to set a Direct3D 11 resource (e.g. a texture or render target) in WPF
+    /// directly because WPF requires Direct3D 9. The <see cref="D3D9"/> class creates a new
+    /// Direct3D 9 device which can be used for sharing resources between Direct3D 11 and Direct3D
+    /// 9. Call <see cref="GetSharedTexture"/> to convert a texture from Direct3D 11 to Direct3D 9.
+    /// </remarks>
+    internal class D3D9 : IDisposable
+    {
+        // The code requires Windows Vista and up using the Windows Display Driver Model (WDDM). 
+        // It does not work with the Windows 2000 Display Driver Model (XDDM).
+
+        #region Fields
+        private bool _disposed;
+        private Direct3DEx _direct3D;
+        private DeviceEx _device;
+        #endregion
+
+
+        #region Creation & Cleanup
+        /// <summary>
+        /// Initializes a new instance of the <see cref="D3D9"/> class.
+        /// </summary>
+        public D3D9()
+        {
+            // Create Direct3DEx device on Windows Vista/7/8 with a display configured to use 
+            // the Windows Display Driver Model (WDDM). Use Direct3D on any other platform.
+            _direct3D = new Direct3DEx();
+
+            PresentParameters presentparams = new PresentParameters
+            {
+                Windowed = true,
+                SwapEffect = SwapEffect.Discard,
+                PresentationInterval = PresentInterval.Default,
+
+                // The device back buffer is not used.
+                BackBufferFormat = Format.Unknown,
+                BackBufferWidth = 1,
+                BackBufferHeight = 1,
+
+                // Use dummy window handle.
+                DeviceWindowHandle = GetDesktopWindow()
+            };
+
+
+            _device = new DeviceEx(_direct3D, 0, DeviceType.Hardware, IntPtr.Zero,
+                                   CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
+                                   presentparams);
+        }
+
+
+        /// <summary>
+        /// Releases unmanaged resources before an instance of the <see cref="D3D9"/> class is 
+        /// reclaimed by garbage collection.
+        /// </summary>
+        /// <remarks>
+        /// This method releases unmanaged resources by calling the virtual <see cref="Dispose(bool)"/> 
+        /// method, passing in <see langword="false"/>.
+        /// </remarks>
+        ~D3D9()
+        {
+            Dispose(false);
+        }
+
+
+        /// <summary>
+        /// Releases all resources used by an instance of the <see cref="D3D9"/> class.
+        /// </summary>
+        /// <remarks>
+        /// This method calls the virtual <see cref="Dispose(bool)"/> method, passing in 
+        /// <see langword="true"/>, and then suppresses finalization of the instance.
+        /// </remarks>
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+
+        /// <summary>
+        /// Releases the unmanaged resources used by an instance of the <see cref="D3D9"/> class 
+        /// and optionally releases the managed resources.
+        /// </summary>
+        /// <param name="disposing">
+        /// <see langword="true"/> to release both managed and unmanaged resources; 
+        /// <see langword="false"/> to release only unmanaged resources.
+        /// </param>
+        protected virtual void Dispose(bool disposing)
+        {
+            if (!_disposed)
+            {
+                if (disposing)
+                {
+                    // Dispose managed resources.
+                    if (_device != null)
+                    {
+                        _device.Dispose();
+                        _device = null;
+                    }
+                    if (_direct3D != null)
+                    {
+                        _direct3D.Dispose();
+                        _direct3D = null;
+                    }
+                }
+
+                // Release unmanaged resources.
+                _disposed = true;
+            }
+        }
+        #endregion
+
+
+        #region Methods
+        
+        [DllImport("user32.dll", SetLastError = false)]
+        private static extern IntPtr GetDesktopWindow();
+
+
+        private void ThrowIfDisposed()
+        {
+            if (_disposed)
+                throw new ObjectDisposedException(GetType().FullName);
+        }
+
+
+        /// <summary>
+        /// Creates Direct3D 9 texture from the specified Direct3D 11 texture. 
+        /// (The content is shared between the devices.)
+        /// </summary>
+        /// <param name="renderTarget">The Direct3D 11 texture.</param>
+        /// <returns>The Direct3D 9 texture.</returns>
+        /// <exception cref="ArgumentException">
+        /// The Direct3D 11 texture is not a shared resource, or the texture format is not 
+        /// supported.
+        /// </exception>
+        public Texture GetSharedTexture(Texture2D renderTarget)
+        {
+            ThrowIfDisposed();
+
+            if (renderTarget == null)
+                return null;
+
+            IntPtr handle = renderTarget.GetSharedHandle();
+            if (handle == IntPtr.Zero)
+                throw new ArgumentException("Unable to access resource. The texture needs to be created as a shared resource.", "renderTarget");
+
+            Format format;
+            switch (renderTarget.Format)
+            {
+                case SurfaceFormat.Bgr32:
+                    format = Format.X8R8G8B8;
+                    break;
+                case SurfaceFormat.Bgra32:
+                    format = Format.A8R8G8B8;
+                    break;
+                default:
+                    throw new ArgumentException("Unexpected surface format. Supported formats are: SurfaceFormat.Bgr32, SurfaceFormat.Bgra32.", "renderTarget");
+            }
+
+            return new Texture(_device, renderTarget.Width, renderTarget.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle);
+        }
+        #endregion
+    }
+}

+ 43 - 0
WpfInteropSample/MainWindow.xaml

@@ -0,0 +1,43 @@
+<Window x:Class="WpfInteropSample.MainWindow"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        xmlns:local="clr-namespace:WpfInteropSample"
+        Title="MainWindow"
+        Width="525"
+        Height="350">
+    <Grid>
+        <Grid.ColumnDefinitions>
+            <ColumnDefinition />
+            <ColumnDefinition />
+        </Grid.ColumnDefinitions>
+        <Grid.RowDefinitions>
+            <RowDefinition />
+            <RowDefinition />
+        </Grid.RowDefinitions>
+
+        <local:D3D11Host x:Name="Host0"
+                         Grid.Row="0"
+                         Grid.Column="0"
+                         Margin="5"
+                         SnapsToDevicePixels="True"
+                         Stretch="Fill" />
+        <local:D3D11Host x:Name="Host1"
+                         Grid.Row="0"
+                         Grid.Column="1"
+                         Margin="5"
+                         SnapsToDevicePixels="True"
+                         Stretch="Fill" />
+        <local:D3D11Host x:Name="Host2"
+                         Grid.Row="1"
+                         Grid.Column="0"
+                         Margin="5"
+                         SnapsToDevicePixels="True"
+                         Stretch="Fill" />
+        <local:D3D11Host x:Name="Host3"
+                         Grid.Row="1"
+                         Grid.Column="1"
+                         Margin="5"
+                         SnapsToDevicePixels="True"
+                         Stretch="Fill" />
+    </Grid>
+</Window>

+ 10 - 0
WpfInteropSample/MainWindow.xaml.cs

@@ -0,0 +1,10 @@
+namespace WpfInteropSample
+{
+  public partial class MainWindow
+  {
+    public MainWindow()
+    {
+      InitializeComponent();
+    }
+  }
+}

+ 55 - 0
WpfInteropSample/Properties/AssemblyInfo.cs

@@ -0,0 +1,55 @@
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("WpfInteropSample")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("WpfInteropSample")]
+[assembly: AssemblyCopyright("Copyright ©  2013")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+//In order to begin building localizable applications, set 
+//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
+//inside a <PropertyGroup>.  For example, if you are using US english
+//in your source files, set the <UICulture> to en-US.  Then uncomment
+//the NeutralResourceLanguage attribute below.  Update the "en-US" in
+//the line below to match the UICulture setting in the project file.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
+    //(used if a resource is not found in the page, 
+    // or application resource dictionaries)
+    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
+    //(used if a resource is not found in the page, 
+    // app, or any theme specific resource dictionaries)
+)]
+
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 71 - 0
WpfInteropSample/Properties/Resources.Designer.cs

@@ -0,0 +1,71 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+//     This code was generated by a tool.
+//     Runtime Version:4.0.30319.18033
+//
+//     Changes to this file may cause incorrect behavior and will be lost if
+//     the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace WpfHost.Properties
+{
+
+
+    /// <summary>
+    ///   A strongly-typed resource class, for looking up localized strings, etc.
+    /// </summary>
+    // This class was auto-generated by the StronglyTypedResourceBuilder
+    // class via a tool like ResGen or Visual Studio.
+    // To add or remove a member, edit your .ResX file then rerun ResGen
+    // with the /str option, or rebuild your VS project.
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    internal class Resources
+    {
+
+        private static global::System.Resources.ResourceManager resourceMan;
+
+        private static global::System.Globalization.CultureInfo resourceCulture;
+
+        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+        internal Resources()
+        {
+        }
+
+        /// <summary>
+        ///   Returns the cached ResourceManager instance used by this class.
+        /// </summary>
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Resources.ResourceManager ResourceManager
+        {
+            get
+            {
+                if ((resourceMan == null))
+                {
+                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfHost.Properties.Resources", typeof(Resources).Assembly);
+                    resourceMan = temp;
+                }
+                return resourceMan;
+            }
+        }
+
+        /// <summary>
+        ///   Overrides the current thread's CurrentUICulture property for all
+        ///   resource lookups using this strongly typed resource class.
+        /// </summary>
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Globalization.CultureInfo Culture
+        {
+            get
+            {
+                return resourceCulture;
+            }
+            set
+            {
+                resourceCulture = value;
+            }
+        }
+    }
+}

+ 117 - 0
WpfInteropSample/Properties/Resources.resx

@@ -0,0 +1,117 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!-- 
+    Microsoft ResX Schema 
+    
+    Version 2.0
+    
+    The primary goals of this format is to allow a simple XML format 
+    that is mostly human readable. The generation and parsing of the 
+    various data types are done through the TypeConverter classes 
+    associated with the data types.
+    
+    Example:
+    
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+                
+    There are any number of "resheader" rows that contain simple 
+    name/value pairs.
+    
+    Each data row contains a name, and value. The row also contains a 
+    type or mimetype. Type corresponds to a .NET class that support 
+    text/value conversion through the TypeConverter architecture. 
+    Classes that don't support this are serialized and stored with the 
+    mimetype set.
+    
+    The mimetype is used for serialized objects, and tells the 
+    ResXResourceReader how to depersist the object. This is currently not 
+    extensible. For a given mimetype the value must be set accordingly:
+    
+    Note - application/x-microsoft.net.object.binary.base64 is the format 
+    that the ResXResourceWriter will generate, however the reader can 
+    read any of the formats listed below.
+    
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with 
+            : System.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+    
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array 
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+</root>

+ 30 - 0
WpfInteropSample/Properties/Settings.Designer.cs

@@ -0,0 +1,30 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+//     This code was generated by a tool.
+//     Runtime Version:4.0.30319.18033
+//
+//     Changes to this file may cause incorrect behavior and will be lost if
+//     the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace WpfHost.Properties
+{
+
+
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
+    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+    {
+
+        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+        public static Settings Default
+        {
+            get
+            {
+                return defaultInstance;
+            }
+        }
+    }
+}

+ 7 - 0
WpfInteropSample/Properties/Settings.settings

@@ -0,0 +1,7 @@
+<?xml version='1.0' encoding='utf-8'?>
+<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
+  <Profiles>
+    <Profile Name="(Default)" />
+  </Profiles>
+  <Settings />
+</SettingsFile>

+ 3 - 0
WpfInteropSample/ReadMe.txt

@@ -0,0 +1,3 @@
+This sample shows how to display MonoGame graphics in a WPF D3DImage.
+
+This sample requires SharpDX >= v2.5.0!

+ 127 - 0
WpfInteropSample/WpfInteropSample.csproj

@@ -0,0 +1,127 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
+    <ProductVersion>8.0.30703</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{B7751FAB-AE42-457F-8D69-51BEE5DC080A}</ProjectGuid>
+    <OutputType>WinExe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>WpfInteropSample</RootNamespace>
+    <AssemblyName>WpfInteropSample</AssemblyName>
+    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+    <TargetFrameworkProfile>Client</TargetFrameworkProfile>
+    <FileAlignment>512</FileAlignment>
+    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <PlatformTarget>x86</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <PlatformTarget>x86</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="SharpDX">
+      <HintPath>..\..\ThirdParty\Libs\SharpDX\Windows\SharpDX.dll</HintPath>
+    </Reference>
+    <Reference Include="SharpDX.Direct3D11">
+      <HintPath>..\..\ThirdParty\Libs\SharpDX\Windows\SharpDX.Direct3D11.dll</HintPath>
+    </Reference>
+    <Reference Include="SharpDX.Direct3D9">
+      <HintPath>..\..\ThirdParty\Libs\SharpDX\Windows\SharpDX.Direct3D9.dll</HintPath>
+    </Reference>
+    <Reference Include="SharpDX.DXGI">
+      <HintPath>..\..\ThirdParty\Libs\SharpDX\Windows\SharpDX.DXGI.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="System.Xaml">
+      <RequiredTargetFramework>4.0</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="WindowsBase" />
+    <Reference Include="PresentationCore" />
+    <Reference Include="PresentationFramework" />
+  </ItemGroup>
+  <ItemGroup>
+    <ApplicationDefinition Include="App.xaml">
+      <Generator>MSBuild:Compile</Generator>
+      <SubType>Designer</SubType>
+    </ApplicationDefinition>
+    <Page Include="MainWindow.xaml">
+      <Generator>MSBuild:Compile</Generator>
+      <SubType>Designer</SubType>
+    </Page>
+    <Compile Include="App.xaml.cs">
+      <DependentUpon>App.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </Compile>
+    <Compile Include="D3D11Image.cs" />
+    <Compile Include="D3D9.cs" />
+    <Compile Include="D3D11Host.cs" />
+    <Compile Include="MainWindow.xaml.cs">
+      <DependentUpon>MainWindow.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </Compile>
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Properties\AssemblyInfo.cs">
+      <SubType>Code</SubType>
+    </Compile>
+    <Compile Include="Properties\Resources.Designer.cs">
+      <AutoGen>True</AutoGen>
+      <DesignTime>True</DesignTime>
+      <DependentUpon>Resources.resx</DependentUpon>
+    </Compile>
+    <Compile Include="Properties\Settings.Designer.cs">
+      <AutoGen>True</AutoGen>
+      <DependentUpon>Settings.settings</DependentUpon>
+      <DesignTimeSharedInput>True</DesignTimeSharedInput>
+    </Compile>
+    <EmbeddedResource Include="Properties\Resources.resx">
+      <Generator>ResXFileCodeGenerator</Generator>
+      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
+    </EmbeddedResource>
+    <None Include="Properties\Settings.settings">
+      <Generator>SettingsSingleFileGenerator</Generator>
+      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
+    </None>
+    <AppDesigner Include="Properties\" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\MonoGame.Framework\MonoGame.Framework.Windows.csproj">
+      <Project>{7DE47032-A904-4C29-BD22-2D235E8D91BA}</Project>
+      <Name>MonoGame.Framework.Windows</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <Resource Include="ReadMe.txt" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>

+ 42 - 0
WpfInteropSample/WpfInteropSample.sln

@@ -0,0 +1,42 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfInteropSample", "WpfInteropSample.csproj", "{B7751FAB-AE42-457F-8D69-51BEE5DC080A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoGame.Framework.Windows", "..\..\MonoGame.Framework\MonoGame.Framework.Windows.csproj", "{7DE47032-A904-4C29-BD22-2D235E8D91BA}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Debug|Mixed Platforms = Debug|Mixed Platforms
+		Debug|x86 = Debug|x86
+		Release|Any CPU = Release|Any CPU
+		Release|Mixed Platforms = Release|Mixed Platforms
+		Release|x86 = Release|x86
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Debug|Any CPU.ActiveCfg = Debug|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Debug|Mixed Platforms.Build.0 = Debug|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Debug|x86.ActiveCfg = Debug|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Debug|x86.Build.0 = Debug|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Release|Any CPU.ActiveCfg = Release|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Release|Mixed Platforms.ActiveCfg = Release|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Release|Mixed Platforms.Build.0 = Release|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Release|x86.ActiveCfg = Release|x86
+		{B7751FAB-AE42-457F-8D69-51BEE5DC080A}.Release|x86.Build.0 = Release|x86
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Debug|x86.ActiveCfg = Debug|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Release|Any CPU.Build.0 = Release|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+		{7DE47032-A904-4C29-BD22-2D235E8D91BA}.Release|x86.ActiveCfg = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal