user868935
user868935

Reputation:

Native OpenGL in winforms panel in WPF

In my project, I already have a native C++ library wrapped in C++\CLI, then referenced in my WPF application. Within my application, I have an aqua-colored Winforms panel displayed:

        <WindowsFormsHost x:Name="openGLWF">
            <winForms:Panel x:Name="openGLPanel1"
                    Dock="Fill" 
                    BackColor="Aqua" Paint="Panel_Paint" />
        </WindowsFormsHost>

What I'm trying to do is have the panel to be used to draw my OpenGL content from my native library. I've search around and through books that hints that it is possible, but the "solutions" I've found are not thorough and are too ambiguous to implement.

NOTE: After being flagged by user gbjbaanb of a possible duplicate that was answered 5 years ago, my issue is different as the "original" that he referenced deals with .NET 4.0 and Winforms, where I'm dealing with .NET 4.5.2 and WPF with a Winforms panel inside of it.

Upvotes: 0

Views: 3187

Answers (1)

BDL
BDL

Reputation: 22175

The workflow is basically the same as with every windows control or window. The only difference is, that one does not have to construct the hwnd since this is already done by the WinForms control. So a example for creating an OpenGL context on a Windows-Forms control could looks like this (C++/CLI):

public void InitGL(System::Windows::Forms::UserControl^ userControl)
{
    HWND hwnd = (HWND)userControl->Handle.ToPointer();
    HDC hdc = GetDC(hwnd);

    //From now on everything is similar to initializing a context on any other hdc
    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory(&pfd, sizeof(pfd));
    pfd.nSize = sizeof(pfd);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |
          PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 24;
    int iFormat = ChoosePixelFormat(hdc, &pfd);
    SetPixelFormat(hdc, iFormat, &pfd);

    HGLRC hrc = wglCreateContext(hdc);
    wglMakeCurrent(hdc, hrc);

    //From now on we have a valid OpenGL context
    //Do other stuff like glewInit etc. now
}

Note, that this code is similar to the one here, which was already linked in the duplicate answer suggestion.

Upvotes: 1

Related Questions