Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.




Creating OpenGL context

  • Include references to System.Windows.Forms and System.Drawing.
  • Include a reference to OpenGL4Net.dll (IMPORTANT! 32 or 64 bit version according to your project properties) or add OpenGL4Net.cs to your project.
  • Optionally use the "using" statement to shorten the syntax

    using System;
    using System.Windows.Forms;
    using OpenGL4Net;
  • It is easier to inherit your class from System.Windows.Forms.Form.

  • Add the RenderingContext as a class variable.
  • Create the Main function that creates an instance of your form, calls the Init function and starts the application with Application.Run method.

    class Program : Form
        RenderingContext rc;
        static void Main(string[] args)
            Program program = new Program();
  • Now create the Init function that creates the rendering context, using the form (this). To avoid flickering in some cases (e.g., changing the size), it is necessary to ignore the WM_ERASEBKGND message. This could be achieved by setting control style AllPaintingInWmPaint to true (or by ignoring WM_ERASEBKGND in WndProc method).

        void Init()
            rc = RenderingContext.CreateContext(this);
            SetStyle (ControlStyles.AllPaintingInWmPaint, true);
  • The Render method should clear the screen and swap front and back buffers

        void Render()
            // here is the right place to draw all your scene
  • If you plan to allow the user to change the window size, you have to update the viewport size and probably make some changes in your projection matrix.

        protected override void OnSizeChanged(EventArgs e)
            gl.Viewport(0,0,ClientSize.Width, ClientSize.Height);
            // change projection matrix etc.
  • Finally, override the WndProc method and call Render method on WM_PAINT message

        protected override void WndProc(ref Message m)
            switch (m.Msg)
                case Windows.WM_PAINT: Render(); break;
                default: base.WndProc(ref m); break;


Wiki: Home

  • jwr

    You may have to call Render() for WM_ERASEBKGND (0x0014) too. If your window has FormBorderStyle of Sizable then you'll need to watch for WM_SIZE (0x0005) messages and update your gl.Viewport accordingly.

    • pet_cz

      Yes, you are right, I just wanted to make the example as simple as possible, but this should be probably mentioned. Thank you.