Jump to content
  • Advertisement
Sign in to follow this  

Unity Window Wrapper - CreateWindow Fails

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

If you intended to correct an error in the post then please contact us.

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
	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);
	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;



#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)
	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)
	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);



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


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

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

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


		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)))

	UpdateWindow (m_hwnd);


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
		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;


//#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);

		return -1;

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

		if(!g_wnd->HandleMessages()) //thus the check in this call fails, killing the app.
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


1>------ Build started: Project: Tempest, Configuration: Debug Win32 ------
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 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
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
Original post by LessBread
When CreateWindow failes, what does GetLastError return?


The parameter is incorrect.


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

Any ideas?


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
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By MintyLyton
      I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website. 
    • By ethancodes
      I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
      Here is the code for the pick up manager:
      // Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
      public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }  
      There is also a Base Pick Up:
      public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed. 
    • By D34DPOOL
      Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
      Posted by D34DPOOL on May 20th, 2018
      Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
      What is required:
      Skill using C#
      Experience with Unity
      Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
      Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
      It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!
      To apply email me at mangemason@yahoo.com
    • By davejones
      Is there a way to automatically change the start position of an animation? I have a bunch of animations set up on 3D models in unity. The issue is that I need to move the 3D models, however when I do so the animation start positions are not updated and I have to do it manually.

      Changing the transform of key frames is time consuming with the amount of animations I have, so I was wondering if there was a way to do it automatically?
    • By MoreLion
      hey all! We are looking for members for our Unity horror game! 
      Here’s the story:
      After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
      This game is not a long development game, I have loads other game ideas,
      I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
      And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
      There is some concept art one of our concept artists have made
      If interested email liondude12@gmail.com
    • By Canadian Map Makers
      GOVERNOR is a modernized version of the highly popular series of “Caesar” games. Our small team has already developed maps, written specifications, acquired music and performed the historical research needed to create a good base for the programming part of the project.

      Our ultimate goal is to create a world class multi-level strategic city building game, but to start with we would like to create some of the simpler modules to demonstrate proof of concept and graphical elegance.


      We would like programmers and graphical artists to come onboard to (initially) create:

      A module where Province wide infrastructure can be built on an interactive 3D map of one of the ancient Roman Provinces.
      A module where city infrastructure can be built on a real 3D interactive landscape.
      For both parts, geographically and historically accurate base maps will be prepared by our team cartographer. Graphics development will be using Blender. The game engine will be Unity.


      More information, and examples of the work carried out so far can be found at http://playgovernor.com/ (most of the interesting content is under the Encyclopedia tab).


      This project represents a good opportunity for upcoming programmers and 3D modeling artists to develop something for their portfolios in a relatively short time span, working closely with one of Canada’s leading cartographers. There is also the possibility of being involved in this project to the point of a finished game and commercial success! Above all, this is a fun project to work on.


      Best regards,

      Steve Chapman (Canadian Map Makers)

    • By Scouting Ninja
      So I have hundreds of moving objects that need to check there speed. One of the reasons they need to check there speed is so they don't accelerate into oblivion, as more and more force is added to each object.
      At first I was just using the Unity vector3.magnitude. However this is actually very slow; when used hundreds of times.
      Next I tried the dot-product check:  vector3.dot(this.transform.foward, ShipBody.velocity) The performance boost was fantastic. However this only measures speed in the forward direction. Resulting in bouncing objects accelerating way past the allowed limit.
      I am hoping someone else knows a good way for me to check the speed with accuracy, that is fast on the CPU. Or just any magnitude calculations that I can test when I get home later.
      What if I used  vector3.dot(ShipBody.velocity.normalized, ShipBody.velocity)?
      How slow is it to normalize a vector, compared to asking it's magnitude?
    • By Ds ds
      Hi, my name is Andres, I'm a programmer with a technician degree and a Diploma in C#, looking for a project in Unity to start my career in game development. I don't do it for a paid but a recognition and start a portfolio, preferably a 2D game. Thanks for read, have a nice day. 
    • By Victor Rodriguez
      Hi there! Is the first time that I'm posting here so I'm sorry if I'm doing it wrong ha. 
      So here it comes, my doubt is, I'm doing a game with different levels, each of these levels in one different scene. Each scene contains to cameras that you can change pressing a button. Everything works fine. 
      The only problem is that I would like it to look a bit more professional, and I would like that if you finish the level with camera2, the next level start the same way. I've been thinking about using dontdestroyonloadon both cameras, but obviously this cameras need to be attached to the player to make the movement work, what do you recommend? Sorry If I've explained it in a messy way, and feel free to dm me for anything. Thanks in advance! 
    • By Ike aka Dk
      Hello everyone 
      I am a programmer from Baku.
      I need a 3D Modeller for my shooter project in unity.I have 2 years Unity exp.
      Project will paid when we finish the work 
      If you interested write me on email:
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
    • Total Posts

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!