Win32 Wrapper - Evil?!

Started by
9 comments, last by GameDev.net 18 years, 4 months ago
Hi, I'm somewhat of a idiot, so far I've had to ask twice for advice; one time on what to do "next", and another time on timed events. (QueryPerformanceCounter vs GetTick vs timeGetTime) Anyway, I need to figure a way how to wrap up all the win32 stuff into some sorta object, or into my engine implement. I'm new to this so I'm designing a "simple" pong engine. (That I will upgrade progressively.) I'm using Windows XP, Directx 9c, and Visual C++ 2005 Professional. I don't want to use stl/mfc. (so far don't need it.) I know windows messages look something like; I sorta want to know how to design this to be effective. My level of expertise goes all the way up to pointers, structures, classes. I still don't understand alot about some things like static functions, and virtual functions. (The win32 wrapper uses stl, and didn't show any working example of code.) Should I be hiding WinMain() and WindowProc() in my engine? I'm sorta new to this. Previously I used SDL where all the Win32 stuff was dealt with inside of SDL. Anyway, my idea was to have something like;
//my engine
include "engine_name.h"

int main(int *argc, char **argv)
{
	//Start my engine.
	engine_name *engine_instance = new engine_name;

	//Init stuff.
	engine_instance->setDebug(true, some_file_path);
	engine_instance->setWindow(fullscreen, yres, xres, bitdepth);
	engine_instance->start();

	//Create a image we can draw.
	image titlescreen = new image(filename);

	//Main game loop.
	while
	{
		//Show the screen.
		titlescreen->Draw(x, y);

		//Render stuff.
		engine_instance->render();

		//Update input?
		engine_instance->inputUpdate();
	}

	//End stuff.
	delete engine_instance;
}
Advertisement
Quote:
Should I be hiding WinMain() and WindowProc() in my engine?


No, not really.
Well, first off, there's nothing wrong with the STL; it's rather efficient at what it does, and is more or less standardized.

But you're asking about Win32 programming. You don't want to wrap WinMain() -- it's the entry point into the program, much like main() is in a non-Win32 program. Essentially, you want a wrapper for the window creation and handling. There is a problem everyone encounters when doing this: WndProc() needs to be a static class function for Windows to call it. Here are three links to guide you (one, two, three). If you haven't created a window by hand before, you will likely get a little lost, but keep MSDN open and look up anything with which you're not familiar, and you should be able to grok what's going on.

And we're always here when you get stuck ;)
I did some simple wrapper, for making some simple OpenGl applications.

So here is the wrapper:
gl_wrap.h
/*    The wrapper is used to simplify GL loading process and other routines    used nehe.gamedev.net source as a reference*//*    The following files are required to include:	opengl32.lib glu32.lib */#ifndef _GL_WRAP_H_#define _GL_WRAP_H_//this should avoid problems with MSVC6 and MSVC2005 unicode standarts#define UNICODE//standart includes#include <windows.h>								// Header File For Windows#include <gl\gl.h>								// Header File For The OpenGL32 Library#include <gl\glu.h>								// Header File For The GLu32 Library#include <gl\glaux.h>								// Header File For The GLaux Library//generally I want to create a class that is easy to work withclass Render{public:	//position of the mouse	int mx;	int my;	//size of the screen	int swidth;	int sheight;	//start and destroy Gl scene    bool Start(int width,int height,bool fullscreen);	void Destroy();    //update window and game events	void Update();	BOOL CreateGLWindow(LPCWSTR title, int width, int height, int bits, bool fullscreenflag);	GLvoid KillGLWindow(GLvoid);		    int DrawGLScene(GLvoid);	int InitGL(GLvoid);	GLvoid ReSizeGLScene(GLsizei width, GLsizei height);				/// CALLBACK METHODS ////	//when drawing the window	void (*OnDraw)(void);	//updating events	void (*OnUpdate)(void);	//when Key Pressed	void (*OnKeyPressed)(unsigned int key);	void (*OnKeyReleased)(unsigned int key);	//Mouse actions	void (*OnMouseMove)(int mx,int my);};#endif


gl_wrap.cpp
#include "gl_wrap.h"HGLRC           hRC=NULL;							// Permanent Rendering ContextHDC             hDC=NULL;							// Private GDI Device ContextHWND            hWnd=NULL;							// Holds Our Window HandleHINSTANCE       hInstance;							// Holds The Instance Of The Applicationbool	keys[256];								// Array Used For The Keyboard Routinebool	active=TRUE;								// Window Active Flag Set To TRUE By Defaultbool	fullscreen=TRUE;							// Fullscreen Flag Set To Fullscreen Mode By DefaultLRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);				// Declaration For WndProc//this should be pointer to our renderRender *rp;//used for resizing GL sceneGLvoid Render::ReSizeGLScene(GLsizei width, GLsizei height)				// Resize And Initialize The GL Window{	if (height==0)								// Prevent A Divide By Zero By	{		height=1;							// Making Height Equal One	}		glViewport(0, 0, width, height);					// Reset The Current Viewport		glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix	glLoadIdentity();							// Reset The Projection Matrix		// Calculate The Aspect Ratio Of The Window	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);		glMatrixMode(GL_MODELVIEW);						// Select The Modelview Matrix	glLoadIdentity();							// Reset The Modelview Matrix}//OpenGL initialisation routineint Render::InitGL(GLvoid)								// All Setup For OpenGL Goes Here{	glShadeModel(GL_SMOOTH);						// Enables Smooth Shading	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);					// Black Background	glClearDepth(1.0f);							// Depth Buffer Setup	glEnable(GL_DEPTH_TEST);						// Enables Depth Testing	glDepthFunc(GL_LEQUAL);							// The Type Of Depth Test To Do	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);			// Really Nice Perspective Calculations	return TRUE;								// Initialization Went OK}int Render::DrawGLScene(GLvoid)								// Here's Where We Do All The Drawing{	if( OnDraw != NULL)	{		OnDraw();	}	return TRUE;								// Everything Went OK}GLvoid Render::KillGLWindow(GLvoid)							// Properly Kill The Window{				if (fullscreen)								// Are We In Fullscreen Mode?	{				ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop		ShowCursor(TRUE);						// Show Mouse Pointer	}		if (hRC)								// Do We Have A Rendering Context?	{				if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?		{						MessageBox(NULL,L"Release Of DC And RC Failed.",L"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		}				if (!wglDeleteContext(hRC))					// Are We Able To Delete The RC?		{						MessageBox(NULL,L"Release Rendering Context Failed.",L"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,L"Release Device Context Failed.",L"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		hDC=NULL;							// Set DC To NULL	}		if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?	{		MessageBox(NULL,L"Could Not Release hWnd.",L"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		hWnd=NULL;							// Set hWnd To NULL	}		if (!UnregisterClass(L"OpenGL",hInstance))				// Are We Able To Unregister Class	{		MessageBox(NULL,L"Could Not Unregister Class.",L"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);		hInstance=NULL;							// Set hInstance To NULL	}}BOOL Render::CreateGLWindow(LPCWSTR title, int width, int height, int bits, bool fullscreenflag){			GLuint		PixelFormat;						// Holds The Results After Searching For A Match		WNDCLASS	wc;							// Windows Class Structure		DWORD		dwExStyle;						// Window Extended Style	DWORD		dwStyle;						// Window Style		RECT WindowRect;							// Grabs Rectangle Upper Left / Lower Right Values	WindowRect.left=(long)0;						// Set 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=fullscreenflag;						// Set The Global Fullscreen Flag		hInstance		= GetModuleHandle(NULL);			// Grab An 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 Messages	wc.cbClsExtra		= 0;						// No Extra Window Data	wc.cbWndExtra		= 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 Required For GL	wc.lpszMenuName		= NULL;						// We Don't Want A Menu	wc.lpszClassName	= L"OpenGL";					// Set The Class Name		if (!RegisterClass(&wc))						// Attempt To Register The Window Class	{		MessageBox(NULL,L"Failed To Register The Window Class.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);		return FALSE;							// Exit And Return FALSE	}		if (fullscreen)								// Attempt Fullscreen Mode?	{				DEVMODE dmScreenSettings;					// Device Mode		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));		// Makes Sure Memory's Cleared		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode 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_FULLSCREEN Gets Rid Of Start Bar.		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)		{						// If The Mode Fails, Offer Two Options.  Quit Or Run In A Window.			if (MessageBox(NULL,L"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?",L"NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)			{								fullscreen=FALSE;				// Select Windowed Mode (Fullscreen=FALSE)			}			else			{								// Pop Up A Message Box Letting User Know The Program Is Closing.				MessageBox(NULL,L"Program Will Now Close.",L"ERROR",MB_OK|MB_ICONSTOP);				return FALSE;					// Exit And Return FALSE			}		}	}		if (fullscreen)								// Are We Still In Fullscreen Mode?	{				dwExStyle=WS_EX_APPWINDOW;					// Window Extended Style		dwStyle=WS_POPUP;						// Windows Style		ShowCursor(FALSE);						// Hide Mouse Pointer	}	else	{				dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style		dwStyle=WS_OVERLAPPEDWINDOW;					// Windows Style	}		AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size		if (!(hWnd=CreateWindowEx(	dwExStyle,				// Extended Style For The Window		L"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,L"Window Creation Error.",L"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 The Display		MessageBox(NULL,L"Can't Create A GL Device Context.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);		return FALSE;							// Return FALSE	}		if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))				// Did Windows Find A Matching Pixel Format?	{		KillGLWindow();							// Reset The Display		MessageBox(NULL,L"Can't Find A Suitable PixelFormat.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);		return FALSE;							// Return FALSE	}		if(!SetPixelFormat(hDC,PixelFormat,&pfd))				// Are We Able To Set The Pixel Format?	{		KillGLWindow();							// Reset The Display		MessageBox(NULL,L"Can't Set The PixelFormat.",L"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,L"Can't Create A GL Rendering Context.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);		return FALSE;							// Return FALSE	}		if(!wglMakeCurrent(hDC,hRC))						// Try To Activate The Rendering Context	{		KillGLWindow();							// Reset The Display		MessageBox(NULL,L"Can't Activate The GL Rendering Context.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);		return FALSE;							// Return FALSE	}		ShowWindow(hWnd,SW_SHOW);						// Show The Window	SetForegroundWindow(hWnd);						// Slightly Higher Priority	SetFocus(hWnd);								// Sets Keyboard Focus To The Window	ReSizeGLScene(width, height);						// Set Up Our Perspective GL Screen		if (!InitGL())								// Initialize Our Newly Created GL Window	{		KillGLWindow();							// Reset The Display		MessageBox(NULL,L"Initialization Failed.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);		return FALSE;							// Return FALSE	}		return TRUE;								// Success}LRESULT CALLBACK WndProc(	HWND	hWnd,					// Handle For This Window				UINT	uMsg,					// Message For This Window				WPARAM	wParam,					// Additional Message Information				LPARAM	lParam)					// Additional Message Information{	switch (uMsg)								// Check For Windows Messages	{		case WM_ACTIVATE:						// Watch For Window Activate Message		{			if (!HIWORD(wParam))					// Check Minimization 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 Powersave?				return 0;					// Prevent From Happening			}			break;							// Exit		}		case WM_CLOSE:							// Did We Receive A Close Message?		{			PostQuitMessage(0);					// Send A Quit Message			return 0;						// Jump Back		}		case WM_KEYUP:							// Has A Key Been Released?		{			keys[wParam] = FALSE;								if( rp->OnKeyReleased != NULL)			{				rp->OnKeyReleased(wParam);			}			return 0;							}		case WM_KEYDOWN:                        //have a key been pressed		{			keys[wParam] = TRUE;  						if( rp->OnKeyPressed != NULL)			{				rp->OnKeyPressed(wParam);			}			return 0;		}		//mouse moving		case WM_MOUSEMOVE:		{			rp->mx = LOWORD(lParam);			rp->my = HIWORD(lParam);			//and set the mouse position			if(rp->OnMouseMove != NULL)			{			rp->OnMouseMove(rp->mx,rp->my);			}			return 0;		}		case WM_SIZE:							// Resize The OpenGL Window		{			rp->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);}void Render::Update(){	MSG	msg;								// Windows Message Structure	BOOL	done=FALSE;							// Bool Variable To Exit Loop	while(!done)								// Loop That Runs Until done=TRUE	{		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))			// Is There A Message Waiting?		{			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?			{				done=TRUE;					// If So done=TRUE			}			else							// If Not, Deal With Window Messages			{				TranslateMessage(&msg);				// Translate The Message				DispatchMessage(&msg);				// Dispatch The Message			}		}		else								// If There Are No Messages		{			// 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						// Not Time To Quit, Update Screen				{					//CALBACK TO OUR UPDATE FUNCTION				    if( OnUpdate != NULL)					{						OnUpdate();					}					DrawGLScene();				// Draw The Scene					SwapBuffers(hDC);			// Swap Buffers (Double Buffering)				}			}		}	}}// GENERAL CLASS ROUTINESbool Render::Start(int width,int height,bool fullscreen){	//clear any callback pointers we are using	OnDraw			= NULL;	OnUpdate        = NULL;	OnKeyPressed	= NULL;	OnKeyReleased	= NULL;	OnMouseMove		= NULL;	swidth			= width;	sheight			= height;	rp = this;	// Create Our OpenGL Window	if (!CreateGLWindow(L"OpenGL Window",width,height,16,fullscreen))	{		return 0;							// Quit If Window Was Not Created	}							// Exit The Program	return true;}void Render::Destroy(){		KillGLWindow();								// Kill The Window}


And here is sample app that calls this class:
#include <stdio.h>//my handy GL wrapper for WINAPI. Easy and Simple#include "gl_wrap.h"//here is gl wrapper classRender render;// DO DRAWING HEREvoid OnDraw(){	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear The Screen And The Depth Buffer	glLoadIdentity();					// Reset The View	glTranslatef(0.0f,0.0f,-3.0f);	//draw some gl	}//PROCESS KEY PRESSED EVENTSvoid OnKeyPressed(unsigned int key){}//UPDATE EVENTSvoid OnUpdate(){   }//ON MOUSE MOVE- recalculate coordiantesvoid OnMouseMove(int mx,int my){}int main(){	//start the GL loader	render.Start(640,480,true);	//specify the callback methods for events	render.OnDraw		= &OnDraw;	render.OnKeyPressed = &OnKeyPressed;	render.OnUpdate		= &OnUpdate;	render.OnMouseMove  = &OnMouseMove;		//start the sequence	render.Update();	render.Destroy();	return 0;}
the way you keep referring to STL I suspect that you really have no idea what it is. The STL is a key part of C++, just as much a part of C++ as is "int" or "while". STL is good and you don't know C++ until you know it, because as I just said, the STL is part of C++. It is not an addon. Well, if this message brings replies I am sorry as I will be gone for quite a while. :(
Quote:Original post by Glak
the way you keep referring to STL I suspect that you really have no idea what it is. The STL is a key part of C++, just as much a part of C++ as is "int" or "while". STL is good and you don't know C++ until you know it, because as I just said, the STL is part of C++. It is not an addon. Well, if this message brings replies I am sorry as I will be gone for quite a while. :(
Actually, STL isn't part of C++. It's just a library of cool data structures that you can use instead of always having to make your own. You don't need to know STL to know C++.

F-R-E-D F-R-E-D-B-U-R...G-E-R! - Yes!
True, the STL is technically not part of C++, but the SC++L (Standard C++ Library), which is what most people actually mean when they refer to the STL, is (at least for a hosted implementation).

Enigma
Quote:Original post by Enigma
True, the STL is technically not part of C++, but the SC++L (Standard C++ Library), which is what most people actually mean when they refer to the STL, is (at least for a hosted implementation).

Enigma
I know exactly what Standard Template Library is. I know what it does. It makes things simplier like linked lists, queues, whatever else. I prefer to write my own data objects. I don't see the exact reason for not doing that. That's all I meant when I said I didn't prefer to use STL since it'd be like for 1-2 win32 calls, and I wouldn't touch it for anything else. It seems irrelavent to add it since I won't use it.

I'm trying to figure a way to encapsulate the win32 code, but I don't quite understand it. I've read several tutorials;
_the only gamedev one_ (doesn't show any *working code, uses the stl, and summarizes things it shouldn't :X )
_codeproject_ (code works! but it has two classes.. a "base", and a "derived", don't get why he used virtual functions - although he said it's "required")
_"generic" win32_ (explains really well, don't know how to integrate with directx, seems like what I have written now.)
Quote:Original post by yckx
[...]There is a problem everyone encounters when doing this: WndProc() needs to be a static class function for Windows to call it. Here are three links to guide you (one, two, three). If you haven't created a window by hand before, you will likely get a little lost, but keep MSDN open and look up anything with which you're not familiar, and you should be able to grok what's going on.
Excellent links, I didn't know about the first two! o.O

I will definitely read your wrapper. (DMINATOR) I'm trying to write a engine, and I think that removing the win32 code is a really smart idea since I'm trying to get rid of anything complicated from the program's starting point. Ah yes, thanks for all the replies :)
Quote:Original post by EmperiorRune
That's all I meant when I said I didn't prefer to use STL since it'd be like for 1-2 win32 calls, and I wouldn't touch it for anything else.

That's an odd statement. You'd only use the STL for a couple Win32 calls? Either you misunderstand something, or I'm really not grokking you. The STL is a C++ library for common data structures (and ways to use and manipulate them), and makes great use of C++ functionality that C doesn't have. Win32 is a C API for Windows programming, and is not designed with STL (or C++) in mind at all. I don't see how one could use the STL for any Win32 calls.

(Okay, one could use std::string.c_str() for the various Win32 char* paramaters, but you should be able to see what I'm saying: nothing in the STL interacts with Win32 and vice versa.)

I can understand wanting to write one's own data scructures as a learning experience, but your statement above is like saying "I'd prefer not to drive a car because I'd only use it to eat peas."
Quote:
I'm trying to figure a way to encapsulate the win32 code


I did this once, here is my main.cpp:

//===============================================#include "winwrap.h"//===============================================class WinBob : public WinWrap{   void OnInit();   void OnDestroy();   void OnKeyDown(int virtual_code, int key_data);};//===============================================void WinBob::OnInit(){	}//===============================================void WinBob::OnDestroy(){		PostQuitMessage(0);}//===============================================void WinBob::OnKeyDown(int virtual_code, int key_data){   switch(virtual_code)   {   	case VK_ESCAPE:      	PostMessage(WM_QUIT, 0, 0);         break;   }}//===============================================int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){   WinBob wb;   wb.init(hInstance, hPrevInstance, lpCmdLine, nCmdShow);   wb.create("Title", WS_VISIBLE | WS_OVERLAPPEDWINDOW, 0, 0, 800, 600);   return wb.run();}//===============================================


The public part of the WinWrap class

...      virtual void OnCreate() {}      virtual void OnInit() = 0;      virtual void OnDestroy() = 0;      virtual void OnIdle() {}      virtual void OnKeyDown(int virtual_code, int key_data) { }      virtual void OnKeyUp(int virtual_code, int key_data) { }      virtual void OnSetCursor(HWND hwnd, WORD nHittest, WORD wMouseMsg) { }      BOOL PostMessage(UINT Msg, WPARAM wParam, LPARAM lParam) { return ::PostMessage(hwnd, Msg, wParam, lParam); }      virtual ~WinWrap();...


and finally the message pump as a static member of WinWrap (as mentioned earlier this must be static)
LRESULT WINAPI WinWrap::msg_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam){	switch(Msg)	{   	case WM_CREATE:      	main_app->OnCreate();         break;      case WM_DESTROY:         main_app->OnDestroy();         break;		case WM_KEYDOWN:      	main_app->OnKeyDown((int)wParam, (int)lParam);         break;      case WM_KEYUP:      	main_app->OnKeyUp((int)wParam, (int)lParam);         break;      case WM_SETCURSOR:      	main_app->OnSetCursor((HWND)wParam, LOWORD(lParam), HIWORD(lParam));         break;    }    return DefWindowProc(hWnd, Msg, wParam, lParam);}

This is incomplete ofcourse...

To make this little scheme work the msg_proc needs a pointer to some instance
of WinWrap... (Im giving WinWrap class a static pointer here, but I believe the use of a singleton could be a better solution)

WinWrap* WinWrap::main_app = NULL;//===============================================WinWrap::WinWrap()	: hinstance(NULL), hwnd(NULL), x(0), y(0), width(640), height(480){	assert(main_app == NULL);      main_app = this;	...}


This constructor is probably doing things a constructor is not supposed to.
Im pretty sure my design is "weak" in many ways, and could be improved in many ways. However it makes my OO design in main.cpp work ^^

[Edited by - pulpfist on November 27, 2005 4:45:45 PM]

This topic is closed to new replies.

Advertisement