Skip to main content
gamedev.net
🔒 Locked

Windows problems again!!!!!

Started by knealeaj 4 replies 750+ views
Original Post
knealeaj
knealeaj
I ahve written a new windows class and got it working ,finally!! I am now trying to implement a way to exit in WinMain(pressing escape).but it does not work (sometimes it does but the majority of the time it doesnt).Here is the code can anyone suggest anything. PS any suggestions for the rest of the code would be appreciated Thanks

#ifndef _WINDOW_H_
#define _WINDOW_H_

//HEADER FILE THAT DEFINES A CLASS FOR THE WINDOW


#define WIN32_LEAN_AND_MEAN						//trim extra fat from windows



//INCLUDES///////////////////////////////////////////////////////////////////

#include <windows.h>							//standard windows app include

#include <gl/gl.h>								//standard OpenGL include

#include <gl/glu.h>								//OpenGL utilities

#include <gl/glaux.h>							//OpenGL auxillary functions

/////////////////////////////////////////////////////////////////////////////



//CLASS DECLERATION//////////////////////////////////////////////////////////

class Window
{
private:
	
	HGLRC hRC;									//rendering context

	

	//The Windows Procedure event handler

	friend LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam);
	//function to set up the pixel format for the device context

	void SetupPixelFormat();

	bool Create();								//WM_CREATE

	void Destroy();								//WM_DESTROY

	void Size();								//WM_SIZE

	void BeginFullscreen(int width,int height,int bits);//start the window in fullscreen

	
public:
	HWND hwnd;									//window handle

	HDC hDC;									//device context

	int width;									//width of window

	int height;									//height of window

	int iPrevWidth;								//previous width of window

	int iPrevHeight;							//previous height of window

	bool fullscreen;							//Fullscreen??

	int bits;									//no of bits

	bool keyDown[256];							//is a key being pressed?

	void EndFullscreen();						//put screen setting back


	//Default Constructor////////////////////////////////////////////////////

	Window(){}
	//Constructor////////////////////////////////////////////////////////////

	Window(const char* windowName,bool fscreen,int w,int h,int b);
	//Destructor/////////////////////////////////////////////////////////////

	~Window();

	//Register Window

	//Must be used before the class is used as it is static

	static bool RegisterWindow(HINSTANCE hInstance);

};





	









#endif





/*/////////////////////////////////////Window.cpp////////////////////////////////////////////

  
					This file includes all the functions to set up the game window

////////////////////////////////////////////////////////////////////////////////////////////*/


#include "Window.h"



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



void Window::SetupPixelFormat()
{
	int pixelFormat;								//the pixel format index


	static PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),				//size of structure

			1,										//version always set to one

			PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,		//support window,opengl and double buffering

			PFD_TYPE_RGBA,							//RGBA colour mode

			32,										//32 bit colour mode

			0,0,0,0,0,0,							//colour bits not used

			0,										//no alpha buffer

			0,										//ignore shift bit

			0,										//no acclumulation buffer

			0,0,0,0,								//ignore accumulation bits

			16,										//16-bit depth buffer

			0,										//no stencil buffer

			0,										//no auxillary buffer

			PFD_MAIN_PLANE,							//main drawing plane

			0,										//reserved

			0,0,0};									//ignore layers mask


		//choose best matching pixel format

		pixelFormat = ChoosePixelFormat(hDC,&pfd);

		//set pixel format to device context

		SetPixelFormat(hDC,pixelFormat,&pfd);

}

//Creates the window

bool Window::Create()
{
	hDC = GetDC(hwnd);								//get windows current device context

	SetupPixelFormat();								//call the pixel format setup function

	//create rendering context and make it current

	hRC = wglCreateContext(hDC);
	wglMakeCurrent(hDC,hRC);

	return true;				//on creation of window retun true




}

//Destroy the window

void Window::Destroy()
{
	if(hwnd != 0)
	{
		if(hDC != 0)
		{
			wglMakeCurrent(hDC,0);
			if(hRC != 0)
			{
				//deselect rendering context and delete it

				wglDeleteContext(hRC);
				hRC = 0;
			}
		
			ReleaseDC (hwnd, hDC);						// Release The Device Context

			hDC = 0;									// Zero The Device Context


		}

		DestroyWindow(hwnd);
		hwnd =0;
	}

	EndFullscreen();

}

//resizing of the window

void Window::Size()
{

	
	if(height ==0)									//dont want to divide by zero

	{
		height =1;
	}

	//reset the viewport to the new dimensions

	glViewport(0,0,width,height);
	glMatrixMode(GL_PROJECTION);					//set the projection matrix

	glLoadIdentity();								//reset projection matrix


	//calculate aspect ratio of window

	gluPerspective(45.0f,(float)width/(float)height,1.0f,1000.0f);

	glMatrixMode(GL_MODELVIEW);						//set matrix mode to modelview

	glLoadIdentity();								//reset modelview matrix

	


}

LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
	Window *OpenGLwindow = (Window*)GetWindowLong(hwnd,GWL_USERDATA);

	

	switch(message)
	{
		case WM_CREATE:
			{
				HINSTANCE hInst = (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE);
				OpenGLwindow = (Window*)(((LPCREATESTRUCT)lParam)->lpCreateParams);

				SetWindowLong(hwnd, GWL_USERDATA, (LONG)OpenGLwindow);

				OpenGLwindow->hwnd = hwnd;

				//create the window

				OpenGLwindow->Create();
			}break;
		case WM_CLOSE:
			{
				//close the window

				OpenGLwindow->Destroy();
				PostQuitMessage(0);

				return 0;
			}break;
		case WM_DESTROY:
			{
				OpenGLwindow->Destroy();
				PostQuitMessage(0);

				return 0;
			}break;
		case WM_SIZE:
			{
				OpenGLwindow->height = HIWORD(lParam);						//retrieve width and height

				OpenGLwindow->width = LOWORD(lParam);

				OpenGLwindow->Size();

				return 0;

			}break;
		case WM_KEYDOWN:
			{
				if ((wParam >= 0) && (wParam <= 255))						// Is Key (wParam) In A Valid Range?

				{
					OpenGLwindow->keyDown[wParam] = TRUE;					// Set The Selected Key (wParam) To True

					return 0;												// Return

				}
			}break;
		case WM_KEYUP:													// Update Keyboard Buffers For Keys Released

			if ((wParam >= 0) && (wParam <= 255))						// Is Key (wParam) In A Valid Range?

			{
				OpenGLwindow->keyDown[wParam] = FALSE;					// Set The Selected Key (wParam) To False

				return 0;												// Return

			}
		break;	

		default :
			break;
	}
	return (DefWindowProc(hwnd,message,wParam,lParam));
}

bool Window::RegisterWindow(HINSTANCE hInstance)
{
	WNDCLASSEX	windowClass;											//the window class


	//fill out the window class structure

	windowClass.cbSize = sizeof(WNDCLASSEX);
	windowClass.style = CS_HREDRAW|CS_VREDRAW;
	windowClass.lpfnWndProc = WndProc;
	windowClass.cbClsExtra = 0;
	windowClass.cbWndExtra = 0;
	windowClass.hInstance = hInstance;
	windowClass.hIcon = LoadIcon(NULL,IDI_APPLICATION);
	windowClass.hCursor = LoadCursor(NULL,IDC_ARROW);
	windowClass.hbrBackground = NULL;
	windowClass.lpszMenuName = NULL;
	windowClass.lpszClassName = "FatHead Engine";
	windowClass.hIconSm = LoadIcon(NULL,IDI_WINLOGO);

	//register the class

	if(!RegisterClassEx(&windowClass))
		return false;

	return true;

}

void Window::BeginFullscreen(int width,int height,int bits)
{

		// Save current display state

		iPrevWidth = GetSystemMetrics(SM_CXSCREEN);
		iPrevHeight = GetSystemMetrics(SM_CYSCREEN);
		
		// Set new display state

		DEVMODE dm;
		memset(&dm, 0, sizeof(dm));
		dm.dmSize	= sizeof(DEVMODE);
		dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
		dm.dmPelsWidth	= width;
		dm.dmPelsHeight = height;
		dm.dmBitsPerPel = bits;
		ChangeDisplaySettings(&dm, CDS_FULLSCREEN);

}

void Window::EndFullscreen()
{
	ChangeDisplaySettings(NULL,0);
}


Window::Window(const char* windowName,bool fscreen,int w,int h,int b)
{
	RECT windowRect;
	DWORD dwStyle;
	DWORD dwExStyle;

	fullscreen = fscreen;
	width = w;
	height = h;
	bits = b;

	windowRect.left = (long)0;
	windowRect.right = (long)width;
	windowRect.top = (long)0;
	windowRect.bottom = (long)height;

	if (fullscreen)
	{
		dwExStyle = WS_EX_APPWINDOW;
		dwStyle = WS_POPUP;
	}
	else
	{
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPEDWINDOW;
	}

	AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle);
	
	// create the window

	if (fullscreen)
	{
		BeginFullscreen(w,h,b);			//start in fullscreen

		//create window

		hwnd = CreateWindowEx(NULL, "FatHead Engine", windowName, dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
						  0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
						  NULL, NULL, (HINSTANCE)GetModuleHandle(NULL), (void*)this);
	}
	else
	{

		hwnd = CreateWindowEx(NULL, "FatHead Engine",windowName, dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
						  0, 0, width, height, NULL, NULL, (HINSTANCE)GetModuleHandle(NULL),(void*)this);
	}


	ShowWindow(hwnd, SW_SHOW);
	UpdateWindow(hwnd);

	
	SetForegroundWindow(hwnd);
	SetCapture(hwnd);
	SetFocus(hwnd);


	ShowCursor(FALSE);

}

Window::~Window()
{
	if(hRC)
		Destroy();

	if(fullscreen)
		EndFullscreen();

	ShowCursor(TRUE);
}





/*//////////////////////////////////WinMain.cpp///////////////////////////////////////////////

  This file is where the function for the main windows entry point is

////////////////////////////////////////////////////////////////////////////////////////////*/



#include <windows.h>
#include "Window.h"
#include "GameMain.h"

#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glu32.lib")
#pragma comment (lib, "glaux.lib") 



int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,
				   int nShowCmd)
{
	
	MSG msg;			//message

	bool done;			//is the application finished

	Window *engineWindow = NULL;	//the engine window

	


	if(!Window::RegisterWindow(hInstance))
	{
		MessageBox(NULL,"Cannot register window class","Error",MB_OK);
		return -1;

	}

	//Declare the window object

	engineWindow = new Window("Fathead Engine",false,640,480,32);

	



	done = false;		//make done equal false to enter loop


	//Main message loop 

	while(!done)
	{
		PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);

		if(msg.message == WM_QUIT)
		{
			done = true;
			delete engineWindow;//when done delete the window object

		}
		else
		{
			if(engineWindow->keyDown [VK_ESCAPE] == TRUE)
			{
				PostMessage (engineWindow->hwnd, WM_QUIT, 0, 0);							// Send A WM_QUIT Message

				done = TRUE;		
			}
				
			TranslateMessage(&msg);			//send event to queue

			DispatchMessage(&msg);
			GameLoop();						//enter the game loop

			SwapBuffers(engineWindow->hDC);	// Swap Buffers (Double Buffering)

		}
	}

	return msg.wParam;

}




peter_b
peter_b
Change this

if(engineWindow->keyDown [VK_ESCAPE] == TRUE)
{
//PostMessage (engineWindow->hwnd, WM_QUIT, 0, 0);

//done = TRUE;


break;
}
[/source
Shields up! Rrrrred alert!
knealeaj
knealeaj
Nope that doesnt work,but thanks
Endurion
Endurion
Change the line

PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);

to

if ( PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE) )

You''re killing your app''s responesness by brute rendering. And you re-send the last message even if there isn''t a new one.
Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>
knealeaj
knealeaj
Thanks that worked a treat.

My problem now is a stack overflow when I delete my window object
.any suggestions



int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,
int nShowCmd)
{

MSG msg; //message

bool done; //is the application finished

Window *engineWindow = NULL; //the engine window




if(!Window::RegisterWindow(hInstance))
{
MessageBox(NULL,"Cannot register window class","Error",MB_OK);
return -1;

}






done = false; //make done equal false to enter loop


//Declare the window object

engineWindow = new Window("Fathead Engine",true,640,480,32);

//Main message loop

while(!done)
{


if(PeekMessage (&msg, engineWindow->hwnd, 0, 0, PM_REMOVE))
{

if(msg.message != WM_QUIT)
{
DispatchMessage(&msg); //dispatch message

TranslateMessage(&msg); //send the event to the queue


if(engineWindow->keyDown [VK_ESCAPE] == TRUE)
{
if(engineWindow->fullscreen)
engineWindow->EndFullscreen();//if the window is fullscreen end fullscreen


done = true;



}

}
}
else
{



GameLoop(); //enter the game loop

SwapBuffers(engineWindow->hDC); // Swap Buffers (Double Buffering)

}

}

delete engineWindow;
return msg.wParam;

}



Endurion
Endurion
Dunno about the stack overflow, but call TranslateMessage before DispatchMessage.
Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.