Wednesday, May 23, 2007

OpenGL in .NET

There is a very simple way how to use OpenGL library in .NET application using C#. The library what you need can be downloaded here The simplest way is to add these downloaded files to your project:

  • csgl.dll
  • csgl.native.dll
See the following "Hello world!" project step by step.

Create a new Windows application project. In the new solution add a new project Class library named GLViewControl. Add csgl.dll and csgl.native.dll to the GLViewControl project and reference csgl.dll library. Reference also System.Windows.Forms and System.Drawing.
Set the "Copy to output directory" property for csgl.native.dll file. Presence of this file in the output directory is important unless you have to install csgl on each system particularly.

Now the project is ready for our code. Add a new class in GLViewControl:

using System;

using CsGL.OpenGL;


namespace GLViewControl


  public class GLView : OpenGLControl


    public override void glDraw()


      GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);// Clear the Screen and the Depth Buffer

      GL.glMatrixMode(GL.GL_MODELVIEW); // Modelview Matrix

      GL.glLoadIdentity();              // reset the current modelview matrix   

      GL.glTranslatef(0.0f, 0.0f, -4.0f); 



        GL.glColor3d(0, 0, 1);

        GL.glVertex3f(-1, -1, 0);

        GL.glColor3d(0, 1, 0);

        GL.glVertex3f(1, -1, 0);

        GL.glColor3d(1, 0, 0);

        GL.glVertex3f(0, 1, 0);




    protected override void InitGLContext()


      GL.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // black background

      GL.glClearDepth(1.0f);                  // depth buffer setup

      GL.glEnable(GL.GL_DEPTH_TEST);          // enables depth testing

      GL.glDepthFunc(GL.GL_LEQUAL);            // type of depth testing

      GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);  // nice perspective calculations           



    protected override void OnSizeChanged(EventArgs e)





      GL.gluPerspective(45.0f, (double)Size.Width / (double)Size.Height, 0.1f, 100.0f);






And now just drag and drop a new GLView control from the toolbox in VS on your form and run the application. The result looks like this:

kick it on

1 comment:

Anonymous said...

Alternatively, there is another C# wrapper package for OpenGL: OpenGL DotNet. Works great for me! You can find it here: