参考链接http://www.opengl.org/wiki/Creating_an_OpenGL_Context

http://www.opengl.org/wiki/Getting_started

有关windows的内容请查阅相关书籍或winsdk。

1.windows下通过C++使用opengl需要链接opengl32.lib库。对应的头文件是wingdi.h。

#include<windows.h>

#include<wingdi.h>

#pragma comment(lib, "opengl32.lib")

为了使工作简单些,使用glew库来加载opengl函数

#include<GL/glew.h>//没有GL文件夹的可以自己创建然后把glew.h放进去
#pragma comment(lib, "glew32.lib")

接下来包含gl.h头文件

#include<GL/gl.h> //必须放在glew.h后面,如果放在前面会报错提示该头文件出现在glew.h前面。没有找到这个文件,但是直接这样写就可以,不知道为什么,知道的人麻烦给个解释哈。

2.有了必要的头文件和库之后接下来就可以来创建一个opengl context了。

为了使用opengl在windows窗口中绘制,需要把一个opengl context和一个windows DC关联起来。

创建一个有CS_OWNDC的windows窗口

......

wndclassEX.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW | CS_SAVEBITS;
......

我们需要在DC支持的pixel format中找出一个和我们期望的opengl context的pixel format最接近的。

用到一个结构PIXELFORMATDESCRIPTOR,在这个结构里描述期望的pixel format

hdc = GetDC(hwnd);

int pf = ChoosePixelFormat(hdc, &pfd); //选择合适的pixel format

用返回的pf设置DC的pixel format

SetPixelFormat(hdc, pf, &pfd);

关联opengl context和DC

HGLRC hglrc = wglCreateContext(hdc);

wglMakeCurrent(hdc, hglrc);

3.现在已经创建了一个opengl context,下面要用glew库加载opengl函数

  // use glew lib to get all opengl and wgl api pointers
  glewExperimental=TRUE;
  GLenum err = glewInit();
  if(err!=GLEW_OK)
  {
   printf("Error: glewInit failed, something is seriously wrong\n");
   return -1000;
  }

4.之后就进入消息循环,可以利用opengl给windows窗口绘制了。