I am a beginner on OpenGL and I created a simple C# project for study.
The openGL functions are imported by PInvoke.
But I found that wglCreateContext always returns 0 at first time after I
choose and set the pixel format. But if I add a call to wglMakeCurrent(0,
0) before wglCreateContext, it will succeed. I rewite the same code in
C++, wglMakeCurrent never needed. Why?
The following is the codes :
bool InitializeOpenGL()
{
Graphics g = CreateGraphics();
//Get the device context associated with graphic.
IntPtr hdc = g.GetHdc();
//Without this line, wglCreateContext will fail.
gl.wglMakeCurrent(hdc, IntPtr.Zero);
PIXELFORMATDESCRIPTOR pfd = new PIXELFORMATDESCRIPTOR();
pfd.nSize = (short)System.Runtime.InteropServices.Marshal.SizeOf(pfd);
pfd.nVersion = 1;
pfd.dwFlags = gl.PFD_DRAW_TO_WINDOW | gl.PFD_DOUBLEBUFFER | gl.PFD_SUPPORT_OPENGL;
pfd.iPixelType = (byte)gl.PFD_TYPE_RGBA;
pfd.iLayerType = (byte)gl.PFD_MAIN_PLANE;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
//choose the pixel format according to the pfd.
int pixelFormat = gl.ChoosePixelFormat(hdc, ref pfd);
//set the format just choosed.
gl.SetPixelFormat(hdc, pixelFormat, ref pfd);
// Create a gl rendering context.
m_hRc = gl.wglCreateContext(hdc);
gl.wglMakeCurrent(hdc, m_hRc);
//release the device context.
g.ReleaseHdc(hdc);
g.Dispose();