c - wglCreateContext 失败并出现错误“像素格式无效”
问题描述
我正在尝试使用上下文访问整个屏幕。
这是我当前的代码(目前只有这个文件):
#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,所以我不确定这里出了什么问题。我该如何解决?
编辑:添加了更多信息
解决方案
您没有设置像素格式。
看看这里的文档。
您应该声明一个像素格式描述符,例如:
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 中也有报道。
因此,您还必须创建自己的 Window,获取其 DC,然后使用它来设置像素格式并创建 GL 上下文。如果你想渲染“全屏”,你只需要创建一个与屏幕大小相同的无边框窗口。我建议在这里查看关于这个问题的这个老问题的答案。
推荐阅读
- bluej - 如何在 BlueJ IDE 中添加 comp102x.IO 包?
- swift4 - 嵌套类的 KeyPath
- php - preg_split 返回整个字符串(unicode)
- python - 从熊猫数据框中删除低频项
- vb.net - 使用 Vb.Net 的右键菜单问题
- javascript - 如何使用php在下拉列表中自动更新三天的日期
- c# - 公开变量时的问题
- java - java slf4j 在 intellij 中失败(没有日志提供程序)但在命令行中运行正常,为什么?
- excel - 如何将特定行数据传输到同一工作簿中的另一张工作表?
- javascript - 尝试用 mocha + nyc 测试功能