LorienGL's picture

Create an OpenGL context over a window that already has one

We are developing a SolidWorks addin that needs to use OpenGL to draw on the SolidWorks window. The problem is that new GraphicsContext returns exception on a window that already has an OpenGL context created (the SolidWorks one) because the SetPixelFormat raises an exception (actually the call to ChoosePixelFormat will be ignored by OpenGL, but the OpenTK framework returns an exception instead). We cannot get the SolidWorks render context handle, only the window handle, so creating it passing the SolidWorks contextHandle is not an option.

We as well tried to create the context using l_GLDC = wglCreateContext(l_G.GetHdc()), and it works correctly but then when we try to create a new GraphicsContext (new ContextHandle(l_GLDC), l_WindowInfo) it gives us an exception of type GraphicsContext (does not specify any error message or anything).

Is there any way to avoid OpenTK raising this exception? Or to create a context without trying to set the pixel format just having the window handle? Or to create a context from another opengl created context using wglCreateContext?

Thnak you very much for your help!!

The code (commented lines are the tests we did):

IntPtr l_SwHWnd = (IntPtr) m_ModelView.GetViewHWnd();
Graphics g = Graphics.FromHwnd(l_SwHWnd);
IWindowInfo l_WinInfo = Utilities.CreateWindowsWindowInfo(l_SwHWnd);
 
//IntPtr hDC = g.GetHdc();
//IntPtr l_OGnContext = wglCreateContext(hDC);
//wglMakeCurrent(hDC, l_OGnContext);
 
//GraphicsContext l_RC = (GraphicsContext)GraphicsContext.CurrentContext;
//GraphicsContext l_RC = GraphicsContext.CreateDummyContext(new ContextHandle(l_OGnContext));
//GraphicsContext l_RC = GraphicsContext.CreateContext(new ContextHandle(l_OGnContext), l_WinInfo);
// GraphicsContext l_RC = GraphicsContext.CreateDummyContext();
 
GraphicsContext l_RC = new GraphicsContext(new GraphicsMode(), l_WinInfo);
 
l_RC.MakeCurrent(l_WinInfo);
l_RC.LoadAll();
GL.Begin(BeginMode.Lines);
GL.Color3(1.0, 0.0, 0.0);
GL.Vertex3(0.0, 0.0, 0.0);
GL.Vertex3(1.0, 1.0, 1.0);
GL.End();
 
l_RC.MakeCurrent(null);
l_RC.Dispose();