wglCreateContext失败,错误“像素格式无效”

时间:2018-04-25 05:26:43

标签: c windows winapi opengl

我正在尝试使用上下文访问整个屏幕。

这是我当前的代码(目前只有这个文件):

#include <stdio.h>
#include <Windows.h>
#include <GL/gl.h>
#include <gl/glu.h>
#include <GL/glext.h>

int main(int argc, char *argv[]) {
    HDC hdc = GetDC(NULL);
    HGLRC hglrc;
    hglrc = wglCreateContext(hdc);

    // Handle errors
    if (hglrc == NULL) {
        DWORD errorCode = GetLastError();
        LPVOID lpMsgBuf;
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            errorCode,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&lpMsgBuf,
            0, NULL );
        printf("Failed with error %d: %s", errorCode, lpMsgBuf);
        LocalFree(lpMsgBuf);
        ExitProcess(errorCode);
    }

    wglMakeCurrent(hdc, hglrc);

    printf("%s\n", (char) glGetString(GL_VENDOR));

    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(hglrc);

    return 0;
}

问题在于此代码的开头:

    HDC hdc = GetDC(NULL);
    HGLRC hglrc;
    hglrc = wglCreateContext(hdc);

和程序的输出(在错误处理if语句中打印)是

Failed with error 2000: The pixel format is invalid.

调用GetDC(NULL)被指定为检索整个屏幕的DC,因此我不确定这里出了什么问题。我该如何解决这个问题?

编辑:添加更多信息

1 个答案:

答案 0 :(得分:2)

您没有设置像素格式。

查看文档here

您应声明像素格式描述符,例如:

PIXELFORMATDESCRIPTOR pfd =
{
    sizeof(PIXELFORMATDESCRIPTOR),
    1,
    PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,    // Flags
    PFD_TYPE_RGBA,        // The kind of framebuffer. RGBA or palette.
    32,                   // Colordepth of the framebuffer.
    0, 0, 0, 0, 0, 0,
    0,
    0,
    0,
    0, 0, 0, 0,
    24,                   // Number of bits for the depthbuffer
    8,                    // Number of bits for the stencilbuffer
    0,                    // Number of Aux buffers in the framebuffer.
    PFD_MAIN_PLANE,
    0,
    0, 0, 0
};

然后使用ChoosePixelFormat获取像素格式编号,例如:

int iPixelFormat = ChoosePixelFormat(hdc, &pfd); 

最后调用SetPixelFormat函数来设置正确的像素格式,例如:

SetPixelFormat(hdc, iPixelFormat, &pfd);

只有这样,你才能调用 wglCreateContext 函数。

<强>更新

正如用户 Chris Becke 指出的那样,无法在屏幕hDC上调用SetPixelFormat(根据OP代码使用GetDC(NULL)获得)。这也在khronos wiki here中报道。

因此,您还必须创建自己的窗口,获取其DC,然后使用它来设置像素格式并创建GL上下文。如果要渲染“全屏”,则只需创建一个屏幕大小相同的无边框窗口。我建议在这里查看this old question关于此问题的答案。

相关问题