# Unity Window Wrapper - CreateWindow Fails

This topic is 4005 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
m_winClass.lpszClassName = "TWindow";

//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>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 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 on other sites
Quote:
 Original post by Gage64Not 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 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 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 on other sites
Quote:
 Original post by LessBreadWhen 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 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 on other sites

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 on other sites
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 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 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 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 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 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 thistypedef 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 exampletypedef 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]

• 10
• 14
• 11
• 10
• 11
• ### Similar Content

• Hello fellow devs!
Once again I started working on an 2D adventure game and right now I'm doing the character-movement/animation. I'm not a big math guy and I was happy about my solution, but soon I realized that it's flawed.
My player has 5 walking-animations, mirrored for the left side: up, upright, right, downright, down. With the atan2 function I get the angle between player and destination. To get an index from 0 to 4, I divide PI by 5 and see how many times it goes into the player-destination angle.

In Pseudo-Code:
angle = atan2(destination.x - player.x, destination.y - player.y) //swapped y and x to get mirrored angle around the y axis
index = (int) (angle / (PI / 5));
PlayAnimation(index); //0 = up, 1 = up_right, 2 = right, 3 = down_right, 4 = down

Besides the fact that when angle is equal to PI it produces an index of 5, this works like a charm. Or at least I thought so at first. When I tested it, I realized that the up and down animation is playing more often than the others, which is pretty logical, since they have double the angle.

What I'm trying to achieve is something like this, but with equal angles, so that up and down has the same range as all other directions.

I can't get my head around it. Any suggestions? Is the whole approach doomed?

Thank you in advance for any input!

• By devbyskc
Hi Everyone,
Like most here, I'm a newbie but have been dabbling with game development for a few years. I am currently working full-time overseas and learning the craft in my spare time. It's been a long but highly rewarding adventure. Much of my time has been spent working through tutorials. In all of them, as well as my own attempts at development, I used the audio files supplied by the tutorial author, or obtained from one of the numerous sites online. I am working solo, and will be for a while, so I don't want to get too wrapped up with any one skill set. Regarding audio, the files I've found and used are good for what I was doing at the time. However I would now like to try my hand at customizing the audio more. My game engine of choice is Unity and it has an audio mixer built in that I have experimented with following their tutorials. I have obtained a great book called Game Audio Development with Unity 5.x that I am working through. Half way through the book it introduces using FMOD to supplement the Unity Audio Mixer. Later in the book, the author introduces Reaper (a very popular DAW) as an external program to compose and mix music to be integrated with Unity. I did some research on DAWs and quickly became overwhelmed. Much of what I found was geared toward professional sound engineers and sound designers. I am in no way trying or even thinking about getting to that level. All I want to be able to do is take a music file, and tweak it some to get the sound I want for my game. I've played with Audacity as well, but it didn't seem to fit the bill. So that is why I am looking at a better quality DAW. Since being solo, I am also under a budget contraint. So of all the DAW software out there, I am considering Reaper or Presonus Studio One due to their pricing. My question is, is investing the time to learn about using a DAW to tweak a sound file worth it? Are there any solo developers currently using a DAW as part of their overall workflow? If so, which one? I've also come across Fabric which is a Unity plug-in that enhances the built-in audio mixer. Would that be a better alternative?
I know this is long, and maybe I haven't communicated well in trying to be brief. But any advice from the gurus/vets would be greatly appreciated. I've leaned so much and had a lot of fun in the process. BTW, I am also a senior citizen (I cut my programming teeth back using punch cards and Structured Basic when it first came out). If anyone needs more clarification of what I am trying to accomplish please let me know.  Thanks in advance for any assistance/advice.

• Hi , I was considering this start up http://adshir.com/, for investment and i would like a little bit of feedback on what the developers community think about the technology.
So far what they have is a demo that runs in real time on a Tablet at over 60FPS, it runs locally on the  integrated GPU of the i7 . They have a 20 000 triangles  dinosaur that looks impressive,  better than anything i saw on a mobile device, with reflections and shadows looking very close to what they would look in the real world. They achieved this thanks to a  new algorithm of a rendering technique called Path tracing/Ray tracing, that  is very demanding and so far it is done mostly for static images.
From what i checked around there is no real option for real time ray tracing (60 FPS on consumer devices). There was imagination technologies that were supposed to release a chip that supports real time ray tracing, but i did not found they had a product in the market or even if the technology is finished as their last demo  i found was with a PC.  The other one is OTOY with their brigade engine that is still not released and if i understand well is more a cloud solution than in hardware solution .
Would there  be a sizable  interest in the developers community in having such a product as a plug-in for existing game engines?  How important  is Ray tracing to the  future of high end real time graphics?

• Good day,

I just wanted to share our casual game that is available for android.

Description: Fight your way from the ravenous plant monster for survival through flips. The rules are simple, drag and release your phone screen. Improve your skills and show it to your friends with the games quirky ranks. Select an array of characters using the orb you acquire throughout the game.