现在像素格式已经设定,下一步工作是产生绘制环境(RC)并使之成为当前绘制环境。在COpenGLDemoView中加入一个保护型的成员函数BOOL CreateViewGLContext(HDC hDC),并加入一个保护型的成员变量HGLRC m_hGLContext;HGLRC是一个指向rendering context的句柄。
BOOL COpenGLDemoView::CreateViewGLContext(HDC hDC)
{
this->m_hGLContext = wglCreateContext(hDC);
if(this->m_hGLContext==NULL)
{//创建失败
return FALSE;
}
if(wglMakeCurrent(hDC,this->m_hGLContext)==FALSE)
{//选为当前RC失败
return FALSE;
}
return TRUE;
}
在OnCreate函数中调用此函数:
int COpenGLDemoView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
HWND hWnd = this->GetSafeHwnd();
HDC hDC = ::GetDC(hWnd);
if(this->SetWindowPixelFormat(hDC)==FALSE)
{
return 0;
}
if(this->CreateViewGLContext(hDC)==FALSE)
{
return 0;
}
return 0;
}
添加WM_DESTROY的消息处理函数Ondestroy( ),使之如下所示:
void COpenGLDemoView::OnDestroy()
{
CView::OnDestroy();
// TODO: Add your message handler code here
if(wglGetCurrentContext()!=NULL)
{
wglMakeCurrent(NULL,NULL);
}
if(this->m_hGLContext!=NULL)
{
wglDeleteContext(this->m_hGLContext);
this->m_hGLContext = NULL;
}
}
最后,编辑COpenGLDemoView的构造函数,使之如下所示:
COpenGLDemoView::COpenGLDemoView()
{
// TODO: add construction code here
this->m_GLPixelIndex = 0;
this->m_hGLContext = NULL;
}
用Classwizard为COpenGLDemoView添加WMSIZE的消息处理函数OnSize,代码如下:
void COpenGLDemoView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
GLsizei width,height;
GLdouble aspect;
width = cx;
height = cy;
if(cy==0)
{
aspect = (GLdouble)width;
}
else
{
aspect = (GLdouble)width/(GLdouble)height;
}
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,500.0*aspect,0.0,500.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
用Classwizard为COpenGLDemoView添加WM_PAINT的消息处理函数OnPaint,代码如下:
void COpenGLDemoView::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CView::OnPaint() for painting messages
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glColor4f(1.0f,0.0f,0.0f,1.0f);
glVertex2f(100.0f,50.0f);
glColor4f(0.0f,1.0f,0.0f,1.0f);
glVertex2f(450.0f,400.0f);
glColor4f(0.0f,0.0f,1.0f,1.0f);
glVertex2f(450.0f,50.0f);
glEnd();
glFlush();
}
评论0