*NEW PROBLEM* Window Creation Error problems in lesson 1

Started by
3 comments, last by Deemo_uk 19 years, 5 months ago
I have just been through the first lesson, reading and then typing out myself. The prog compiles and runs but after i select to go into full screen or not, the error checking part of the code returns the "Failed to Register the Window Class." error. I have downloaded the code and that runs fine, any one have any ideas what i've missed?
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//INCLUDES
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <windows.h>			//Windows header file
#include <gl\gl.h>				//OpenGL32 header file
#include <gl\glu.h>				//GLu32 header file
#include <gl\glaux.h>			//GLaux header file

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//OpenGL Globals
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

HGLRC		hRC = NULL;			//Permenant Rendering Context
HDC			hDC = NULL;			//Private GDI Device Context
HWND		hWnd = NULL;		//Holds Window Handle
HINSTANCE	hInstance;			//Holds the Instance of the App

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//GLOBAL VARIABLES
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool	keys[256];				//Array to monitor the keyboard
bool	active = true;			//Flag to set if the window is active, true by default
bool	fullscreen = true;		//Flag to set fullscreen mode set to true by default

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DECLERATIONS
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );			//Declaration for WndProc

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//Function to resize window//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
GLvoid resizeGLScene( GLsizei width, GLsizei height )
{
	if ( height == 0 )										//Stops a devision by zero
	{
		height = 1;											//By making height equal to one
	}

	glViewport( 0, 0, width, height);						//Resets the viewport

	glMatrixMode( GL_PROJECTION );							//Deals with the Projection Matrix
	glLoadIdentity();										//Initialises it

	//Calculate aspect ratio of window
	gluPerspective( 45.0f, (GLfloat) width/ (GLfloat) height, 0.1f, 100.0f );

	glMatrixMode( GL_MODELVIEW );							//Deals with the Modelview matrix
	glLoadIdentity();										//Initialises it
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//Initialise function for all OpenGL/////////////////////////////////////////////////////////////////////////////////////////////////////////////
int initGL()
{
	glShadeModel( GL_SMOOTH );					//Sets the shade model to Smooth by default could also be GL_FLAT
	glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );	//Sets the backround colour, black at the moment

	glClearDepth(1.0f);				//Sets the Depth Buffer
	glEnable( GL_DEPTH_TEST );		//Activates Depth Testing
	glDepthFunc( GL_LEQUAL );		//Sets the type of depth testing

	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );	//Sets OpenGL to give a nice looking perspective

	return true;	//Init went ok
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//Deals with all OpenGL Drawing//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int drawGLScene()
{
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );	//Clears the screen and depth buffer
	glLoadIdentity();										//Reset the modelview matrix
	return true;											//Drawing went ok
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//Function to properly close the window//////////////////////////////////////////////////////////////////////////////////////////////////////////
GLvoid killGLWindow()
{
	if (fullscreen)											//Are we in fullscreen?
	{
		ChangeDisplaySettings( NULL, 0 );					//If we are the drop back 2 the desktop
		ShowCursor(true);
	}


	if (hRC)												//Do we have a rendering context?	
	{
		
		if( !wglMakeCurrent( NULL, NULL ) )					//Can we release the DC and RC context?
		{
			MessageBox( NULL, "Release of DC and RC Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION );	//Displays an error mesage if we can't release the rendering context
		}


		if( !wglDeleteContext(hRC) )						//Are we able to delete teh RC?
		{
			MessageBox( NULL, "Release Rendering COntext Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION );
		}
		hRC = NULL;											//Set RC to NULL
	}


	if ( hDC && !ReleaseDC( hWnd, hDC) )					//Are we able to release the DC?
	{
		MessageBox( NULL, "Release Device Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION );
		hDC = NULL;											//Set DCto NULL
	}


	if ( hWnd && !DestroyWindow(hWnd) )						//Are we able to destroy the window?
	{
		MessageBox( NULL, "Could Not Release hWnd.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
		hWnd = NULL;										//Set hWnd to NULL
	}

	if ( !UnregisterClass( "OpenGL", hInstance ) )		//Are we able to Unregister Class
	{
		MessageBox( NULL, "Could Not Unregister Class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION );
		hInstance = NULL;
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//Function to create the Window//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool createGLWindow( char* title, int width, int height, int bits, bool full_screen_flag)
{
	
	GLuint		PixelFormat;				//Holds the results after searching for a pixel format match
	WNDCLASS	wc;							//Windows Class Structure

	DWORD		dwExstyle;					//Window exstended style
	DWORD		dwstyle;					//Window style

	RECT		WindowRect;					//Takes rectangle Upper left & Lower Right Vlaues
	WindowRect.left = (long)0;				//Set the left value to 0
	WindowRect.right = (long)width;			//Set right value to requested width
	WindowRect.top = (long)0;				//Set top value to 0
	WindowRect.bottom = (long)height;		//Set bottom value to requested height

	fullscreen = full_screen_flag;			//Set the glabal fullscreen flag

	hInstance			= GetModuleHandle(NULL);				//Grab the instance for our window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	//Redraw on Move and own DC for window
	wc.lpfnWndProc		= (WNDPROC) WndProc;					//WndProc Handles Message
	wc.cbClsExtra		= 0;									//No Extra Window Data
	wc.cbClsExtra		= 0;									//No Extra Window Data
	wc.hInstance		= hInstance;							//Set the instance
	wc.hIcon			= LoadIcon( NULL, IDI_WINLOGO);			//Load the default Icon
	wc.hCursor			= LoadCursor( NULL, IDC_ARROW);			//Load the arrow pointer
	wc.hbrBackground	= NULL;									//No background requiured for GL
	wc.lpszMenuName		= NULL;									//Don't want a menu
	wc.lpszClassName	= "OpenGL";								//set the class name

	if ( !RegisterClass( &wc ) )		//Attempt to register the window class
	{
		MessageBox( NULL, "Failed to Register the Window Class.", "ERROR", MB_OK | MB_ICONINFORMATION);
		return false;					//Exit and return false.
	}

	if ( fullscreen )													//Attempt fullscreen mode?
	{
		DEVMODE dmScreenSettings;										//Device Mode
		memset( &dmScreenSettings, 0, sizeof( dmScreenSettings ) );		//Make sure the memory is cleared
		dmScreenSettings.dmSize = sizeof( dmScreenSettings );			//Size of the devmod structure
		dmScreenSettings.dmPelsWidth	=	width;						//Selected screen width
		dmScreenSettings.dmPelsHeight	=	height;						//Selected screen height
		dmScreenSettings.dmBitsPerPel	=	bits;						//Selected bits per pixel
		dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

		//Try  to set selected mode and get results. NOTE: CDS_FULSCREEN gets rid of start bar.
		if ( ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN ) != DISP_CHANGE_SUCCESSFUL)
		{
			//If the mode fails, Offer Two Options. Quit or run in window
			if (MessageBox( NULL, "The requested fullscreen mode is not supported by\nYour Video Card. Use windowed mode instead?", "GL", MB_YESNO | MB_ICONEXCLAMATION ) ==IDYES)
			{
				fullscreen = false;		//Selcect Windowed Mode (Fullscreen = False)
			}
			else
			{
				//Give a message to the user to let them know the program is closing
				MessageBox( NULL, "Program will now close.", "ERROR", MB_OK | MB_ICONSTOP );
				return false;			//Exit and return false
			}
		}
	}

	if ( fullscreen )			//Are we still in fullscreen?
	{
		dwExstyle = WS_EX_APPWINDOW;			//Window exstended style
		dwstyle = WS_POPUP;						//Window style
		ShowCursor( false );					//Hide Mouse Pointer
	}
	else
	{
		dwExstyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			//Window exstended style
		dwstyle = WS_OVERLAPPEDWINDOW;							//Window style
	}

	AdjustWindowRectEx( &WindowRect, dwstyle, false, dwExstyle );		//Adjust window to true requested size

	if ( !(hWnd=CreateWindowEx	(	dwExstyle,							// Extended style For The Window
									"OpenGL",							// Class Name
									title,								// Window Title
									WS_CLIPSIBLINGS |					// Required Window style
									WS_CLIPCHILDREN |					// Required Window style
									dwstyle,							// Selected Window style
									0, 0,								// Window Position
									WindowRect.right-WindowRect.left,	// Calculate Adjusted Window Width
									WindowRect.bottom-WindowRect.top,	// Calculate Adjusted Window Height
									NULL,								// No Parent Window
									NULL,								// No Menu
									hInstance,							// Instance
									NULL								// Don't Pass Anything To WM_CREATE
								)))								
	{
		killGLWindow();		//Reset the Display
		MessageBox( NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return false;		//Return false
	}

	static	PIXELFORMATDESCRIPTOR pfd=					// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),					// Size Of This Pixel Format Descriptor
		1,												// Version Number
		PFD_DRAW_TO_WINDOW |							// Format Must Support Window
		PFD_SUPPORT_OPENGL |							// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,								// Must Support Double Buffering
		PFD_TYPE_RGBA,									// Request An RGBA Format
		bits,											// Select Our Color Depth
		0, 0, 0, 0, 0, 0,								// Color Bits Ignored
		0,												// No Alpha Buffer
		0,												// Shift Bit Ignored
		0,												// No Accumulation Buffer
		0, 0, 0, 0,										// Accumulation Bits Ignored
		16,												// 16Bit Z-Buffer (Depth Buffer)
		0,												// No Stencil Buffer
		0,												// No Auxiliary Buffer
		PFD_MAIN_PLANE,									// Main Drawing Layer
		0,												// Reserved
		0, 0, 0											// Layer Masks Ignored
	};


	if ( !( hDC=GetDC( hWnd ) ) )						//Did we get a device context?
	{
		killGLWindow();									//Reset Display
		MessageBox( NULL, "Can't create a GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;
	}

	if ( !( PixelFormat = ChoosePixelFormat( hDC, &pfd ) ) )	//Did windows find a matching Pixel Format?
	{
		killGLWindow();			//Reset the display
		MessageBox( NULL, "Can't find sutiable Pixel Format.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;			//Return false
	}

	if ( !( hRC = wglCreateContext( hDC ) ) )				//Are we able to get a rendering context
	{
		killGLWindow();			//Reset the Display
		MessageBox( NULL, "Can't Creat a GL Rendering Context", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;			//Return false
	}

	if ( !wglMakeCurrent( hDC, hRC ) )
	{
		killGLWindow();			//Reset the Display
		MessageBox( NULL, "Can't activate the GL Rendering Context", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;			//Return false
	}

	ShowWindow( hWnd, SW_SHOW );			//Show the window
	SetForegroundWindow( hWnd );			//Slightly higer priority
	SetFocus( hWnd );						//Sets keyboard focus to the window
	resizeGLScene( width, height);			//Set up our Perspective GL Screen

	if ( !initGL() )						//Initialise our new window
	{
		killGLWindow();						//Reset the Display
		MessageBox( NULL, "Initialisation Failed", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;						
	}

	return true;				//Sucsessful
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Function to handle windows messages////////////////////////////////////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK WndProc(	HWND	hwnd,					//Handle for this Window
							UINT	uMsg,					//Message for this window
							WPARAM	wParam,					//Additional message info
							LPARAM	lParam)					//Additional message info
{
	switch( uMsg )			//Check for windows messages
	{

		case WM_ACTIVATE:		//Watch for window active messages
			{
				if( !HIWORD( wParam ) )		//Check minimisation state
				{
					active = true;			//Program is Active
				}
				else
				{
					active = false;			//Program is no longer active
				}

				return 0;					//Return to the message loop
			}


		case WM_SYSCOMMAND:				//Intercept System Commands
			{
				switch (wParam)				//Check System Calls
				{
					case SC_SCREENSAVE:		//Screensaver Trying to Start?
					case SC_MONITORPOWER:	//Monitor trying to enter Power Save?
					return 0;				//Prevent from Happening
				}
				break;						//Exit
			}


		case WM_CLOSE:					//Did we recive a close message?
			{
				PostQuitMessage(0);		//Send a quit message
				return 0;				//Jump Back
			}

		case WM_KEYDOWN:				//Is a key being held down?
			{
				keys[wParam] = true;	//If so, mark it as TRUE
				return 0;				//Jump Back
			}

		case WM_KEYUP:					//Is a key being held down?
			{
				keys[wParam] = false;	//If so, mark it as FALSE
				return 0;				//Jump Back
			}

		case WM_SIZE:											//Resize the OpenGl window
			{
				resizeGLScene(LOWORD(lParam), HIWORD(lParam));	//LoWord = Width, HiWord = Height
				return 0;										//Jump Back
			}
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);

}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//####MAIN PROGRAM####
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(		HINSTANCE		hInstance,				//Instance
						HINSTANCE		hPrevInstance,			//Previous Instance
						LPSTR			lpCmdLine,				//Command Line Parameters
						int				nCmdShow)				//Window Show State
{
	MSG		msg;			//Windows Message Structure
	bool	done = false;	//Variable to exit loop, false means that the program has not finished yet

	//Ask user which screen mode they prefer
	if ( MessageBox( NULL, "Would you like to run in fullsceen mode?", "Fullscreen?", MB_YESNO | MB_ICONQUESTION == IDNO ) )
	{
		fullscreen = false;			//Windowed Mode
	}

	//Create OpenGL Window
	if ( !createGLWindow( "Deemo's Asteroids", 800, 600, 32, fullscreen ) )
	{
		return 0;					//Quit if window is not created
	}


	while ( !done )					//Loop runs until done = TRUE
	{
		if ( PeekMessage ( &msg, NULL, 0,0, PM_REMOVE ) )		//Is the a message waiting?
		{
			if ( msg.message == WM_QUIT )			//Have we got a quit message?
			{
				done = true;						//If so done = TRUE
			}
			else
			{
				TranslateMessage( &msg );			//Translate the Message
				DispatchMessage( &msg );			//Dispatch the Message
			}
		}
		else
		{
			//Draw the scene. Watch for ESC key and quit messages From drawGLScene()
			if ( active )							//Program Active
			{
				if ( keys[VK_ESCAPE] )				//Was ESC Pressed?
				{
					done = true;					//ESC Signalled a Quit
				}
				else								//No Quit, Update Screen
				{
					drawGLScene();					//Draw the Scene
					SwapBuffers( hDC);				//Swap Buffers (Double Buffering)
				}
			}

			if ( keys[VK_F1] )						//Is F1 being pressed?
			{
				keys[VK_F1] = false;				//If so make it false
				killGLWindow();						//Kill our current window
				fullscreen = !fullscreen;			//Toggle fullscreen / windowed
				
				//Recreate OpenGL Window
				if ( !createGLWindow( "Deemo's Asteroids", 800, 600, 32, fullscreen ) )
				{
					return 0;					//Quit if window is not created
				}
			}
		}
	}
	//Shutdown
	killGLWindow();			//Kill the window
	return ( msg.wParam );	//Exit the Program
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//####END OF MAIN PROGRAM####
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[Edited by - Deemo_uk on November 9, 2004 5:05:54 AM]
Advertisement
In future when posting large code segments please use [source] tags (and [code] tags for small code snippets).

I suspect your problem stems from this:
wc.lpfnWndProc = (WNDPROC) WndProc; //WndProc Handles Messagewc.cbClsExtra = 0; //No Extra Window Datawc.cbClsExtra = 0; //No Extra Window Datawc.hInstance = hInstance; //Set the instance

You've made a copy/paste error and set wc.cbClsExtra twice and not set wc.cbWndExtra at all, leaving it at an undefined and probably invalid value. That might not be the only problem but it's the first one I spotted.

Enigma
Thanks for that, thats sorted the problem on the Window Class Registration. Now i'm gettin the 'Window Creation Error', any ideas?

P.S Sorry about the long code posting

[Edited by - Deemo_uk on November 9, 2004 4:21:16 AM]
That was a tough one to debug. Your code is:
HWND		hWnd = NULL;		//Holds Window Handle//codeLRESULT CALLBACK WndProc(	HWND	hwnd,					//Handle for this Window							UINT	uMsg,					//Message for this window							WPARAM	wParam,					//Additional message info							LPARAM	lParam)					//Additional message info//code	return DefWindowProc(hWnd,uMsg,wParam,lParam);

whereas the working code is:
HWND		hWnd=NULL;		// Holds Our Window Handle// codeLRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window							UINT	uMsg,			// Message For This Window							WPARAM	wParam,			// Additional Message Information							LPARAM	lParam)			// Additional Message Information//code	return DefWindowProc(hWnd,uMsg,wParam,lParam);

Note the varying capitalisation on the 'w' of hwnd. Your code is using the global hwnd, not the hWnd passed as a parameter.

Once you've fixed that you'll find you're also missing:
	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?	{		KillGLWindow();								// Reset The Display		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);		return FALSE;								// Return FALSE	}

from between your ChoosePixelFormat and wglCreateContext calls.

Enigma
Thanks man, i couldn't for the life of me see where the problem was!? Comparing it to the downloaded code it seemed identical! Thanks again for pointing out the missing bits to.

This topic is closed to new replies.

Advertisement