Sign in to follow this  
_Sigma

Unity Window Wrapper - CreateWindow Fails

Recommended Posts

After much pain, and using another resource, I finally got my window wrapper to actually compile. Much happiness ensued. yet, when I run my code, CreateWindow(...) fails. The API call within the TWindow::Show() call. There are warnings generated about pointer truncation, which I would love to be solved as well. So, I'm going to post my whole code in the hopes that someone with more experience can point me in the right direction, as I am getting very frustrated with this! Which is never good! So if you have any idea, post!!! I will be very grateful! TWindow.h
#ifndef TWINDOW_H
#define TWINDOW_H

#include <Windows.h>
#include <WindowsX.h>
#include <map>
#include "TRESULT.h"

#define CLASSNAME "TWindow"
class TWindow;

typedef long (* tyMessageHandler)(TWindow &,HWND, long, long);
typedef std::map<long, tyMessageHandler> tyMessageMap;
typedef tyMessageMap::iterator tyMessageIterator;

class TWindow
{
public:
	TWindow(HINSTANCE hInstance);
	TRESULT Create(DWORD style,int width, int height);

	static LRESULT CALLBACK dfMsgRouter(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
	//LRESULT CALLBACK MsgRouter(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);

	tyMessageIterator GetMessageHandler(long message);
	tyMessageHandler RegisterMessageHandler(long message,tyMessageHandler handler);
	void SetHWND(HWND hwnd);
	bool IsExit();
	TRESULT Show();
	bool TWindow::HandleMessages();

	//static member functions
	static long OnClose(TWindow &wnd,HWND hwnd, long param0, long param1);
	static long OnDestroy(TWindow &wnd, HWND hwnd, long param0, long param1);

	int ExitCode();
	void SetExitCode(long code);
private:
	tyMessageMap m_MsgHandlers;
	bool m_exit; // true = exiting
	HWND m_hwnd;
	WNDCLASSEX m_winClass; //Main windows class
	HINSTANCE m_hInstance;
	long m_exitCode;
	DWORD m_style;
	int m_height;
	int m_width;


};

#endif



TWindow.cpp
#include "TWindow.h"

void TWindow::SetHWND(HWND hwnd)
{
	m_hwnd = hwnd;
}

bool TWindow::IsExit()
{
	return m_exit;
}

// Window::OnClose is a static method called in response to WM_CLOSE
long TWindow::OnClose(TWindow &wnd,HWND hwnd, long param0, long param1)
{
	DestroyWindow(hwnd);
	return 0;
}

// Window::OnDestroy is a static method called in response to WM_DESTROY
long TWindow::OnDestroy(TWindow &wnd,HWND hwnd, long param0, long param1)
{
	PostQuitMessage(0);
	return 0;
}

TRESULT TWindow::Create(DWORD style,int width, int height)
{
	HWND hwnd = 0;

	m_winClass.cbSize = sizeof(WNDCLASSEX);
	m_winClass.style =  CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
	m_winClass.lpfnWndProc = TWindow::dfMsgRouter;
	m_winClass.cbClsExtra = 0;
	m_winClass.cbWndExtra = 4;
	m_winClass.hInstance = this->m_hInstance;
	m_winClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	m_winClass.hCursor = LoadCursor(NULL, IDC_ARROW);
	m_winClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	m_winClass.lpszMenuName = NULL;
	m_winClass.lpszClassName = "TWindow";
	m_winClass.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
	
	//register the window
	if (!RegisterClassEx (&m_winClass))
	{
		MessageBox (NULL, TEXT ("RegisterClassEx failed!"), "Error", MB_ICONERROR);
		return(T_WND_CREATE_FAIL);
	}

	this->SetHWND(hwnd);

	this->RegisterMessageHandler(WM_CLOSE,&TWindow::OnClose);
	this->RegisterMessageHandler(WM_DESTROY,&TWindow::OnDestroy);

	m_style = style;
	m_height = height;
	m_width = width;

	return(T_OK);
}

// Window::HandleMessage ties everything together
bool TWindow::HandleMessages()
{
	static MSG msg;

	if(!m_hwnd)
	{
		m_exitCode = -1;
		//throw std::runtime_error(std::string("Window not yet created"));
		return false;
	}

	PeekMessage(&msg, m_hwnd, 0, 0, PM_REMOVE);

	::TranslateMessage(&msg);
	::DispatchMessage(&msg);


	if(IsExit())
	{
		SetExitCode((long)msg.lParam);
		return false;
	}


	return true;
}

void TWindow::SetExitCode(long code)
{
	m_exitCode = code;
}
TWindow::TWindow(HINSTANCE hInstance)
{
	m_hInstance = hInstance;
	m_exitCode = 0;
}

tyMessageIterator TWindow::GetMessageHandler(long message)
{
	// m_MsgHandlers is a tyMessageMap instance
	tyMessageIterator it = m_MsgHandlers.find(message);
	if(it == m_MsgHandlers.end())
		return NULL;
	return it;
}

tyMessageHandler TWindow::RegisterMessageHandler(long message,
												tyMessageHandler handler)
{
	tyMessageHandler m = NULL;
	tyMessageIterator it = m_MsgHandlers.find(message);
	if(it != m_MsgHandlers.end())
		m = it->second;
	m_MsgHandlers.insert(std::pair<long,tyMessageHandler>(message, handler));
	return m;
}

TRESULT TWindow::Show()
{
	if(!(m_hwnd = CreateWindow(NULL, "TWindow", m_style, 0,0,m_width,m_height, NULL, NULL, m_hInstance, (void*)this)))
		return(T_WND_CREATE_FAIL);

	UpdateWindow (m_hwnd);

	return(T_OK);
}

LRESULT CALLBACK TWindow::dfMsgRouter(HWND hwnd, UINT message,
								   WPARAM wparam, LPARAM lparam)
{
	
	
	TWindow* pWnd;

	if (message == WM_NCCREATE)
		::SetWindowLong(hwnd, GWL_USERDATA, (long)((LPCREATESTRUCT(lparam))->lpCreateParams));

	
	// get the pointer to the window
	pWnd = (TWindow *)GetWindowLong(hwnd, GWL_USERDATA);

	// if we have the pointer, go to the message handler of the window
	// else, use DefWindowProc
	if(pWnd)
	{
		tyMessageIterator it;
		it = pWnd->GetMessageHandler(message);
		if(it != NULL)
			return (it->second)((*pWnd), hwnd, wparam, lparam);
	}
	
	return DefWindowProc(hwnd, message, wparam, lparam);
}

int TWindow::ExitCode()
{
	return m_exitCode;

}



main.cpp
//#include <windows.h>

#include "TWindow.h"


static TWindow *g_wnd;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
   
	g_wnd = new TWindow(hInstance);
	g_wnd->Create(WS_OVERLAPPEDWINDOW|WS_VISIBLE,400,400);

	if(!g_wnd)
		return -1;

	g_wnd->Show(); //this call fails

	while(true)
	{
		if(!g_wnd->HandleMessages()) //thus the check in this call fails, killing the app.
			break;
	}
return g_wnd->ExitCode();

}



The error code thing is

#ifndef TRESULT_H
#define TRESULT_H

/************************************************************************/
/* Defines the return codes used by the tempest endinge                                                                     */
/************************************************************************/

typedef unsigned int TRESULT;


#define T_OK 0x0 //generic ok
#define T_ERROR 0x1 //generic error
#define T_WND_CREATE_FAIL 0x2 //window failed to create

#endif




1>------ Build started: Project: Tempest, Configuration: Debug Win32 ------
1>Compiling...
1>TWindow.cpp
1>c:\documents and settings\chris\my documents\programming\c++\tempest\working source\twindow.cpp(162) : warning C4311: 'type cast' : pointer truncation from 'LPVOID' to 'long'
1>c:\documents and settings\chris\my documents\programming\c++\tempest\working source\twindow.cpp(166) : warning C4312: 'type cast' : conversion from 'LONG' to 'TWindow *' of greater size
1>c:\documents and settings\chris\my documents\programming\c++\tempest\working source\twindow.cpp(175) : warning C4244: 'argument' : conversion from 'LPARAM' to 'long', possible loss of data
1>c:\documents and settings\chris\my documents\programming\c++\tempest\working source\twindow.cpp(175) : warning C4244: 'argument' : conversion from 'WPARAM' to 'long', possible loss of data
1>Linking...
1>Embedding manifest...
1>Build log was saved at "file://c:\Documents and Settings\Chris\My Documents\Programming\C++\Tempest\Builds\Intermediate\BuildLog.htm"
1>Tempest - 0 error(s), 4 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========


Many thanks!!

Share this post


Link to post
Share on other sites
Not sure where the problem is, but I see two suspecious things:

1) Why are you setting m_winClass.cbWndExtra to 4? usually it is set to 0 (sorry if I'm missing something, I don't have a lot of experience with Windows programming)

2) In main(), you check if g_wnd isn't null, but if it was, your code would crash when calling g_wnd->Create(...). If anything, you should check it after the call to new to see if the allocation was successful.

Share this post


Link to post
Share on other sites
Quote:
Original post by Gage64
Not sure where the problem is, but I see two suspecious things:

1) Why are you setting m_winClass.cbWndExtra to 4? usually it is set to 0 (sorry if I'm missing something, I don't have a lot of experience with Windows programming)

2) In main(), you check if g_wnd isn't null, but if it was, your code would crash when calling g_wnd->Create(...). If anything, you should check it after the call to new to see if the allocation was successful.


1. I thought this needed to be 4 so you can store the extra info?

2. D'oh! Should fix that. Thanks for pointing that out. Although this isn't the cause of the error afaik....

Share this post


Link to post
Share on other sites
Regarding the WM_NCCREATE event, MSDN says:

"If an application processes this message, it should return TRUE to continue creation of the window. If the application returns FALSE, the CreateWindow or CreateWindowEx function will return a NULL handle".

Any chance that this is what's causing the problem? (I also tried looking for info on cbWndExtra but couldn't find any).

Another thing is that GetMessageHandler() takes a (signed) long as a parameter while a message is represented as a UINT (unsigned), which might cause problems (I kinda doubt it but still...).

Share this post


Link to post
Share on other sites
From a semantic perspective, the Show method should simply toggle the display of the window on and off not create it and update it. Window creation should be done in a Create method. The method that you've named Create deals with registering the window class not creating the window. It might be better named Initialize.

Inside HandleMessages you might want to check the return value from PeekMessage to determine if there is a message and if so then call ::TranslateMessage(&msg); and ::DispatchMessage(&msg); As it stands now you have a loop that calls those once every time through and that's overkill. Those functions only need to be called when there is a message to pass along.


pWnd = (TWindow *)GetWindowLong(hwnd, GWL_USERDATA);

That's an old style type cast, fine for C but not for C++.

When CreateWindow failes, what does GetLastError return?

Share this post


Link to post
Share on other sites
Quote:
Original post by LessBread
When CreateWindow failes, what does GetLastError return?

87


The parameter is incorrect.


ERROR_INVALID_PARAMETER

WTF. Does anything jump out at you guys? I thought that perhaps the (void*)this was the culprit, but I guess not.

Any ideas?

Cheers

Share this post


Link to post
Share on other sites
The first parameter isn't supposed to be NULL is it? ;)

If you change it from NULL to "TWindow" (the name that is registered) it just crashes in the main message loop. Any ideas?

Share this post


Link to post
Share on other sites
I would use CreateWindowEx instead.

With CreateWindow, the first argument is the name of the window class that you registered earlier. So the NULL for first parameter is likely the problem. Swap it with "TWindow".

If that causes it to crash in the message loop, then there's a problem with the message loop. Start with a simple message loop and once you get that working move to a more complex message loop.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
I couldn't get my Windows wrapper to work _until_ I used CreateWindowEx as you needed to pass the "this" pointer with the last parameter. Also the 4 extra bits is to hold info and is correct (or allowed). I get the same warnings you're talking about either with C or C++ casting. I just disable them.

Share this post


Link to post
Share on other sites
Looks like CreateWindowEx was the ticket here. I pretty much got rid of all the code in the main callback, so it was always calling defProc and it get a screen!

Big issue is a crash in the MsgRouter when we look in the MessageMap. Big STL errors are thrown. Can anyone point me in the right direction here? Line in question is:


tyMessageIterator it;
it = pWnd->GetMessageHandler(message);
if(it != NULL)
return (it->second)((*pWnd), hwnd, wparam, lparam);



it comes back as

- it {first=??? second=??? } std::_Tree&lt;std::_Tmap_traits&lt;long,long (__cdecl*)(TWindow &,HWND__ *,long,long),std::less&lt;long&gt;,std::allocator&lt;std::pair&lt;long const ,long (__cdecl*)(TWindow &,HWND__ *,long,long)&gt; &gt;,0&gt; &gt;::iterator
- ptr {first=??? second=??? } std::pair&lt;long const ,long (__cdecl*)(TWindow &,HWND__ *,long,long)&gt;
first CXX0030: Error: expression cannot be evaluated
second CXX0030: Error: expression cannot be evaluated


Share this post


Link to post
Share on other sites
I think you need to fix this

typedef long (* tyMessageHandler)(TWindow &,HWND, long, long);

to match the signature of a class method rather than a _cdecl function.

typedef long (TWindow::* tyMessageHandler)(HWND, long, long);

Typedefed names sometimes append _t or T rather than prepend. For example

typedef long (TWindow::* MessageHandlerT)(HWND, long, long);

and if you're going to use HWND, you might as well use WPARAM, LPARAM and LRESULT too.

typedef LRESULT (TWindow::* MessageHandlerT)(HWND, WPARAM, LPARAM);

but nothing says you have to.

Share this post


Link to post
Share on other sites
Changing that, I needed to un-static the 2 member functions OnClose and OnDestroy. Doing this, this line
			return (it->second)((hwnd, wparam, lparam);

generates this error:
1>c:\documents and settings\chris\my documents\programming\c++\tempest\working source\twindow.cpp(188) : error C2064: term does not evaluate to a function taking 3 arguments


Which is kinda whack.

Thinking this through, I don't think that I want to use member function signature, but rather use the _cdecl as then one doesn't have to modify the class to add other routines. So I think that I'll just have ptr to functions.

So given this, any other suggestions? Or is my logic flawed?

Share this post


Link to post
Share on other sites
I'd have to think it all through as well, but isn't part of the point of wrapping a window in a class to be able to extend that class? So wouldn't you want to stay away from static methods?

Share this post


Link to post
Share on other sites
Well I think the way Oluseyi did it with the map was so that you didn't have to inherit off a base class like the 2nd link in my OP.

One just creates the base class and then one can do as many OnClose, OnPain, etc events as one wanted by just creating a small function that is called on that message, and registering it.

So yes, I think in this case we want to stay away from static functions. As well I don't think that
Quote:

I think you need to fix this

typedef long (* tyMessageHandler)(TWindow &,HWND, long, long);

to match the signature of a class method rather than a _cdecl function.

typedef long (TWindow::* tyMessageHandler)(HWND, long, long);

Typedefed names sometimes append _t or T rather than prepend. For example

typedef long (TWindow::* MessageHandlerT)(HWND, long, long);

and if you're going to use HWND, you might as well use WPARAM, LPARAM and LRESULT too.

typedef LRESULT (TWindow::* MessageHandlerT)(HWND, WPARAM, LPARAM);

but nothing says you have to.

Is what I want to do, as I don't want to be tied down by having to have an event handler in the class.


edit
tracing, and setting a bp on if(it != NULL), first trace through all is fine, seccond time through, it comes back null, as expected, but then the test on it (it != NULL) is what causes the big STL error.

tyMessageIterator it;
it = pWnd->GetMessageHandler(message);

if(it != NULL) <- HERE
return (it->second)((*pWnd), hwnd, wparam, lparam);




[Edited by - _Sigma on March 8, 2007 9:02:25 AM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this