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
:::C#
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.
:::C#
class Program : Form
{
RenderingContext rc;
static void Main(string[] args)
{
Program program = new Program();
program.Init();
Application.Run(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).
:::C#
void Init()
{
rc = RenderingContext.CreateContext(this);
SetStyle (ControlStyles.AllPaintingInWmPaint, true);
}
- The Render method should clear the screen and swap front and back buffers
:::C#
void Render()
{
gl.Clear(GL.COLOR_BUFFER_BIT);
// here is the right place to draw all your scene
rc.SwapBuffers();
}
- 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.
:::C#
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
:::C#
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case Windows.WM_PAINT: Render(); break;
default: base.WndProc(ref m); break;
}
}
}
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.
Yes, you are right, I just wanted to make the example as simple as possible, but this should be probably mentioned. Thank you.