Solved - render a scene with screen space geometry to bitmap

Aug 20, 2013 at 4:21 AM
In case if anybody will struggle with this - if you are trying to render a viewport to a bitmap without displaying it on screen, and the scene contains some screen space geometry (like LinesVisual3D) - this geometry is absent in the resulting bitmap. This is because CompositionTarget.Rendering event gets never fired in drawing-to-bitmap mode.

This is my dirty as hell solution to this - call this function before your render-to-bitmap code:
        void InvokeRenderingEvent()
        {
            // For those about to hack

            var mediaContextType = typeof(MatrixTransform).Assembly.GetType("System.Windows.Media.MediaContext");

            var fromMethod = mediaContextType.GetMethod("From", BindingFlags.Static | BindingFlags.NonPublic);
            var renderingField = mediaContextType.GetField("Rendering", BindingFlags.Instance | BindingFlags.NonPublic);

            var mediaContext = fromMethod.Invoke(null, new object[] { Dispatcher.CurrentDispatcher });

            var eventDelegate = (MulticastDelegate)renderingField.GetValue(mediaContext);

            if (eventDelegate != null)
            {
                foreach (var handler in eventDelegate.GetInvocationList())
                {
                    handler.Method.Invoke(handler.Target, new object[] { null, EventArgs.Empty });
                }
            }
        }
Hope this will help someone,
Yevgeni.