« Laszlo! | Main | indistinguishable from magic (more on .net/c++ windows development) »

C++ OpenGL rendering to .NET control

Dana and I worked through some OpenGL setup stuff, and we got C++ OpenGL calls rendering to my .NET control. I get the HDC in C# from the PaintEventArgs, and pass the HDC through to my C++ OpenGL rendering code... and it draws! Mostly.

With my current code, I only see the opengl-painted stuff when I minimize, then maximize the window; my opengl code gets called every paint event, but it only gets drawn visibly after a maximize event. I'm not yet very worried about this, because I'm making a new wglContext every paint event, which is not ideal. My next step is to make one wglContext for a ManagedWindow, and reuse it for subsequent redraws.

Here's the most important nugget of the code

// C#
// Paint handler for my .NET control
private void LeoControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
System.IntPtr hdc = e.Graphics.GetHdc();
// Call the C++ internals to render some stuff onto this widget.
CSCppWrapper wrapper = new CSCppWrapper();
// initHDC also draws some test stuff into the HDC

// C++
CppInternals::initHDC(HDC hdc)
_hdc = hdc;

// create and enable the render context (RC)
_hrc = wglCreateContext( _hdc );

int format;

// set the pixel format for the DC
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat( _hdc, &pfd );
SetPixelFormat( _hdc, format, &pfd );


// pair with create context call.
wglDeleteContext( _hrc);


CppInternals::renderScene() {

// Tell it to render to the context we initialized in initHDC
wglMakeCurrent( _hdc, _hrc );

// make some opengl calls here to draw stuff
// ....

// Actually put this opengl stuff on the screen!
// Except, this doesn't seem to actually put the stuff on the screen... I don't think.

// Let go of this context
wglMakeCurrent( NULL, NULL);


This makes me so very very happy.

Reader Comments (1)

I was wondering if you ever tried rendering directly to a Windows.Forms form window instead of a child control.

I have gotten rendering to a control to work, but when I try to use the window handle of the form instead, all I get is a black form...

1.20.2006 at 10:46 AM | Unregistered CommenterMichael McHenry

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>