OpenGL Engine in a WPF hosted Window.

Wpf OpenGL

I have been working on my editor as of late in hopes of being able to use it to make my simple demo I have been talking about. I found a lot of doubt on the internet about the ability to interop OpenGL with the WPF rendering stack.

Well, we got it to work and it is very similar to the setup I had used to get it working in WinForms. Here is how we did it. First of all, you need a 3D Engine with the ability to take an HWND and use that for rendering. A complete tutorial on how to do this can be found in a gamedev article here.

Once you get this far, its only a matter of creating some xaml.

        <Window x:Class="GravEdit.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="GravEdit" Height="800" Width="800">
    <WindowsFormsHost x:Name="OpenGlPanel"/>        
    </Window>

And your C# for this xaml would look something like:

public partial class MainWindow : Window
        {
            private GravWrap gravWrap = new GravWrap(); //an instance of the engine
            ILua LuaPortal;
 
        public MainWindow()
            {
                InitializeComponent();
                System.Windows.Forms.Panel panel = new System.Windows.Forms.Panel();
                this.OpenGlPanel.Child = panel; //add the winform panel as a child to the winformhost
                IntPtr LuaState = this.gravWrap.Initialize(panel.Handle.ToInt32()); //pass the panels hwnd.

We created a Panel within the WinformsHost and that was it.

Cheers!

Leave a Reply