【问题标题】:wglCreateContext fails with error "The pixel format is invalid"wglCreateContext 失败并出现错误“像素格式无效”
【发布时间】:2018-10-05 11:27:58
【问题描述】:

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

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

#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,所以我不确定这里出了什么问题。我该如何解决这个问题?

编辑:添加更多信息

【问题讨论】:

  • 您在哪里选择和设置像素格式?

标签: c windows winapi opengl


【解决方案1】:

您没有设置像素格式。

查看文档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 中报告。

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

【讨论】:

  • 值得补充的是,不能设置桌面窗口的像素格式。您必须创建自己的窗口。
  • 谢谢,我没注意到。我相应地更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2021-11-12
  • 2010-11-22
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 2016-12-07
  • 2012-09-24
  • 2023-03-21
相关资源
最近更新 更多