Hi, I want to draw in a window using a thread.
I wrote a working function which draws using OpenGL functions but it doesn’t work - the window is white and empty.
When I try to put glGetError in the function I got ony “Invalid operation”. How do I fix the code? thank you.
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
HWND hWnd;
HDC hDC;
HGLRC hRC;
HANDLE thread;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void EnableOpenGL();
void DisableOpenGL();
DWORD WINAPI DrawScene(LPVOID lpParameter);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = "glthreads";
RegisterClass(&wc);
hWnd = CreateWindow("glthreads", "glthreads", WS_OVERLAPPEDWINDOW,
150,100,500,500, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
EnableOpenGL();
thread = CreateThread(NULL,0,DrawScene,NULL,0,NULL);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
DisableOpenGL();
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
void EnableOpenGL()
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
hDC = GetDC(hWnd);
ZeroMemory( &pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat(hDC,&pfd);
SetPixelFormat(hDC,iFormat,&pfd);
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC,hRC);
glClearColor(0.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-20,20,-20,20);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0,0,500,500);
}
void DisableOpenGL()
{
wglMakeCurrent( NULL, NULL );
wglDeleteContext(hRC);
ReleaseDC(hWnd,hDC);
}
DWORD WINAPI DrawScene(LPVOID lpParameter)
{
glClearColor(0.0,0.0,0.0,0.0);
glClear(GL_COLOR_BUFFER_BIT);
glRotatef(1.0,0,0,1);
glBegin(GL_POLYGON);
glColor3f(1.0,0.0,0.0);
glVertex2f(0.0,0.0);
glColor3f(0.0,1.0,0.0);
glVertex2f(10.0,0.0);
glColor3f(0.0,0.0,1.0);
glVertex2f(10.0,10.0);
glEnd();
glFinish();
glFlush();
SwapBuffers(hDC);
return 0;
}