问题描述
- 以mfc为框架的opengl,为什么连背景都没有显示啊。 5C
- 自己按照网上的尝试了下mfc框架的opengl,但是根本就没有绘图,连背景都没有显示。求帮助。以下是代码,我自己创建了一个继承CWnd的类,如下:
C/C++ codeIMPLEMENT_DYNAMIC(COpenGL CWnd)
COpenGL::COpenGL()
{}
COpenGL::~COpenGL()
{
wglMakeCurrent(NULLNULL);
wglDeleteContext(hglrc);
::ReleaseDC(m_hWndhdc);
}BEGIN_MESSAGE_MAP(COpenGL CWnd)
ON_WM_CREATE()
ON_WM_PAINT()
END_MESSAGE_MAP()// COpenGL 消息处理程序
int COpenGL::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;// TODO: 在此添加您专用的创建代码MySetPixelFormat(::GetDC(m_hWnd));hdc = ::GetDC(m_hWnd);hglrc = wglCreateContext(hdc);CRect rect;this->GetWindowRect(&rect);wglMakeCurrent(hdchglrc);glShadeModel(GL_SMOOTH);glClearColor(1.0f1.0f1.0f1.5f);glClearDepth(1.0f);glEnable(GL_DEPTH_TEST);glDepthFunc(GL_LEQUAL);glHint(GL_PERSPECTIVE_CORRECTION_HINT GL_NICEST);glViewport (0 0 rect.Width()rect.Height());glMatrixMode (GL_PROJECTION);glLoadIdentity ();gluPerspective(65.0 (GLfloat)rect.Width()/(GLfloat)rect.Height() 1 1000);glMatrixMode(GL_MODELVIEW);glLoadIdentity();return 0;
}
void COpenGL::OnPaint()
{
//CPaintDC dc(this); // device context for painting
// TODO: 在此处添加消息处理程序代码
// 不为绘图消息调用 CWnd::OnPaint()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //清除颜色缓存和深度缓存
glLoadIdentity();gluLookAt(052 000 001);glColor3f(0.5f0.5f1.0f); // 一次性将当前色设置为蓝色glBegin(GL_QUADS); // 绘制正方形glVertex3f(300.0f 300.0f 0.0f);glVertex3f(300.0f -300.0f 0.0f);glVertex3f(-300.0f -300.0f 0.0f);glVertex3f(-300.0f 300.0f 0.0f);glEnd();SwapBuffers(hdc);
}
int COpenGL::MySetPixelFormat(HDC hdc)
{
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR)
PFD_DRAW_TO_WINDOW|
PFD_SUPPORT_OPENGL|
PFD_DOUBLEBUFFER
PFD_TYPE_RGBA
0 0 0 0 0 0
0
0
0
0 0 0 0
32
0
0
PFD_MAIN_PLANE
0
0 0 0
};int iPixelFormat;if(iPixelFormat = ChoosePixelFormat(hdc&pfd) == 0){ ::MessageBox(NULLChoosePixelFormat Failed""error""MB_OK); return 0;}if(SetPixelFormat(hdciPixelFormat&pfd)){ ::MessageBox(NULLSetPixelFormat Failed""error""MB_OK); return 0;}return 1;
}
另外 在主对话框中有如下代码:
C/C++ codeBOOL CMyProjectDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();// 将“关于...”菜单项添加到系统菜单中。// IDM_ABOUTBOX 必须在系统命令范围内。ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){ BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING IDM_ABOUTBOX strAboutMenu); }}// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动// 执行此操作SetIcon(m_hIcon TRUE); // 设置大图标SetIcon(m_hIcon FALSE); // 设置小图标// TODO: 在此添加额外的初始化代码CRect rect;GetDlgItem(IDC_STATIC)->GetWindowRect(rect);ScreenToClient(rect);m_pDisplay->Create(NULL NULL WS_CHILD|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_VISIBLE rect this 0);return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}