# Strange Win32 problem

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

## Recommended Posts

Hello, first of all thank you for reading this topic. I'm currently in the progress of writing a Win32 wrapper, named OOWin32. It's shaping up nicely, considering it's my first attempt to write a wrapper for Win32. Now, I'm having a strange problem, CreateWindowEx returns an invalid handle, but doesn't set LastError code. After some research, I've found out that it's the Window Proc that's at fault, so I thought: "Doh, forgot to turn any unhandled events to DefWindowProc" but when I checked, I noticed the window proc _was DefWindowProc. So that made no sense. I wrote a quick window proc that showed a message box (and returned the result of DefWindowProc), but it didn't even show the message box. And with that, I've just eleminated the only case I found on the internet that had my specific problems, CreateWindowEx not returning a valid handled and not setting the last error. This is my initialize function (it's virtual, and it get's called in my system).
	bool Window::initialize()
{
WNDCLASSA wc;

HINSTANCE hInstance = GetModuleHandle(NULL);

this->class_name = ("OOWin32Window@" + (boost::format("%#x")%this).str()).c_str();

wc.style         = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc   = (WNDPROC)Util::WndProc;
wc.cbClsExtra    = 0;
wc.cbWndExtra    = 0;
wc.hInstance     = hInstance;
wc.hbrBackground = (HBRUSH)GetStockObject(COLOR_WINDOW);
wc.lpszClassName = this->class_name.c_str();

// Register the application
if(!RegisterClassA(&wc))
{
MessageBoxA(NULL, boost::lexical_cast<std::string>(GetLastError()).c_str(), "Error in RegisterClass", MB_OK);
destroy();
WindowManager::getInstance()->removeWindow(this);
return false;
}

RECT WindowRect;
WindowRect.left= rect.x;
WindowRect.top = rect.y;
WindowRect.right=rect.w;
WindowRect.top = rect.h;

// Find a function that can directly adjust the window

//SetLastError(0);
this->handle = 0;
HWND hWnd = CreateWindowExA(
dwExStyle,							// Extended Style For The Window
this->class_name.c_str(),					// Class Name
title.c_str(),						// Window Title
dwStyle |							// Defined Window Style
WS_CLIPSIBLINGS |					// Required Window Style
WS_CLIPCHILDREN,					// Required Window Style
WindowRect.left, WindowRect.top,	// Window Position
WindowRect.right-WindowRect.left,	// Calculate Window Width
WindowRect.bottom-WindowRect.top,	// Calculate Window Height
NULL,								// No Parent Window
hInstance,							// Instance
NULL);								// Window Long, used to pass along for user data.
this->handle = (void*)hWnd;
if(!hWnd)
{
MessageBoxA(reinterpret_cast<HWND>(handle), ("ERROR!\n" + boost::lexical_cast<std::string>(GetLastError())).c_str(), "Window::initialize", MB_OK);
destroy();
WindowManager::getInstance()->removeWindow(this, false);
return false;
}

return true;
}


Some extra info, dwstyle is set to WS_OVERLAPPEDWINDOW, dwExstyle is set to: WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, the bounds are 10, 10, 800, 600 (x,y,w,h format). As you can see, I've uncommented the SetLastError(0) just before the CreateWindowEx, I've done that because I could set it to anything and it wouldn't matter. If you think it's the that my window class is a WNDCLASSA and I've using the Extended version of CreateWindow, then I'm afraid I have to proof you wrong, this is a very valid thing to do. Not to mention, I've tried every combination.:P I hope you can find the culprit of the problem, I think it's going to be something small...:( Thank you for your time. [EDIT] I would also like to say that the setting the window visible is done only if this function returns true, which doesn't happen.

##### Share on other sites
Quote:
 Original post by mldaalderAfter some research, I've found out that it's the Window Proc that's at fault, so I thought: "Doh, forgot to turn any unhandled events to DefWindowProc" but when I checked, I noticed the window proc _was DefWindowProc.

No it isn't...
Quote:
 wc.lpfnWndProc = (WNDPROC)Util::WndProc;

I'm guessing your window proc is misbehaving as your research suggested or that it is not a static member function and thus you end up getting garbage passed to it.

##### Share on other sites
It's the test window proc I've mentioned.

	LRESULT	CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wparam, LPARAM lparam)	{		MessageBoxA(hWnd, "Test WndProc", "TEST!", MB_OK);		return DefWindowProc(hWnd, msg, wparam, lparam);	}

But the MessageBox is never called.

##### Share on other sites
I've read that article in the past, but it isn't quite what I'm looking for (need more widgets). Though it has been half a year ago.

The strange problem is, that _none_ of the places I have message handling routines, is being called on window creation.

I have tried some more, and it's the window creation where it get's wrong, the oter places don't get called yet (for instance, the window manager's PumpMessage routine, which basicly get's all the messages and routes them to the message handlers, but this requires created windows).

Ok, a bit more about the system.

In my main I do the following:
	OOWin32::WindowManagerPtr winManager = OOWin32::WindowManager::getInstance();	OOWin32::Window* testwindow = winManager-&gt;createWindow();	testwindow-&gt;setBounds(0,0, 800, 600);	testwindow-&gt;setTitle("OOWin32 Test Window 1");	testwindow-&gt;setstyle(WS_OVERLAPPEDWINDOW);	testwindow-&gt;setExtendedstyle(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE);	testwindow-&gt;setVisible(true);	MessageBoxA(NULL, "Test", "Main", MB_OK);	return winManager-&gt;PumpMessages();

The functions up until setVisible aren't important (they can do some window work, but only if the widget is initialized, a widget can be anything, from a button to a window, to something abstract, such as a container).

setVisible does the following:
	void Window::setVisible(bool isVisible)	{		Container::setVisible(isVisible);		if(isVisible)		{			HWND hWnd = reinterpret_cast<HWND>(getHandle());			if(hWnd)			{				ShowWindow(hWnd,SW_SHOW);				SetForegroundWindow(hWnd);				SetFocus(hWnd);			}		}	}

Container::setVisible does some child layout, but it also calls the Widget::setVisible, which does the initialization (if needed).

	void Widget::setVisible(bool isVisible)	{		visible = isVisible;		if(!handle)			if(!this->initialize())					return;		if(wid_pimpl_->parent)		{			wid_pimpl_->parent->doLayout(wid_pimpl_->parent->getIterator(this));		}	}

I'm using the Pimpl idiom (aka compiler firewall, as described by the guru of the week website, since I would otherwise have a cyclic dependancy between Widget and Container (Container inherits from Widget)).

initialize is a virtual function, and brings me full circle with the function in my first post.

##### Share on other sites
Its not clear from the code but does the initialize() function get called during the winManager.createWindow() function? If so then you haven't specified the style flags before trying to create the window. At least from the main snippit you've shown.

Not critical but any reason your specifically using the ANSI versions of the Win32 API? The windows headers have macros to select the right version depending on Unicode/Ansi. i.e. use MessageBox() instead of MessageBoxA()

##### Share on other sites
Quote:
 Original post by mark_devIts not clear from the code but does the initialize() function get called during the winManager.createWindow() function? If so then you haven't specified the style flags before trying to create the window. At least from the main snippit you've shown.

Look back at the first post, I'm using WS_OVERLAPPEDWINDOW as the dwstyle and WS_EX_APPWINDOW | WS_EX_WINDOWEDGE as the dwExstyle.

The setVisible calls initialize if it hasn't been initialized already.

Check my post above yours for the run down how it gets to initialize.

Quote:
 Not critical but any reason your specifically using the ANSI versions of the Win32 API? The windows headers have macros to select the right version depending on Unicode/Ansi. i.e. use MessageBox() instead of MessageBoxA()

I know this, and I've used the Ansi function explicitly in case I wanted to switch some parts to Unicode later, which will save me some work instead of having to _T all the explicit parts and using some ugly per character wchar_t casting (haven't found the correct way of doing yet :().
Should have done it from the start, but that would break some other code as well (atleast, in the project where this library is intended for).

In a lot of other projects I've used the correct way.
But at the moment, it's no big deal.

##### Share on other sites
this->class_name = ("OOWin32Window@" + (boost::format("%#x")%this).str()).c_str();

Maybe you're assigning class_name to the c_str() pointer of a temporary string returned from operator+( const char*, string ).

##### Share on other sites
Quote:
 Original post by JaymarIf I'm reading this right:*** Source Snippet Removed ***Maybe you're assigning class_name to the c_str() pointer of a temporary string returned from operator+( const char*, string ).

Woops, was a typo.

Still, it's not the problem, since I've also tried it with a non dynamic class name.

I've fixed it now, and it's giving me the same problem.

On another forum it was suggested that it's the window rect.

After some tests, this "appears", like the best code to do this:
		long screenW = GetSystemMetrics(SM_CXSCREEN);		RECT screenRect;		SystemParametersInfo(SPI_GETWORKAREA, 0, &screenRect, 0);		long screenH = GetSystemMetrics(SM_CYSCREEN) - (GetSystemMetrics(SM_CYSCREEN)-screenRect.bottom);		RECT WindowRect;		WindowRect.left= rect.x;		WindowRect.top = rect.y;		WindowRect.right=screenW - (rect.w+rect.x);		WindowRect.bottom = screenH - (rect.h+rect.y);

It results into this after the AdjustWindowEx:
---------------------------
Test
---------------------------
-4x-26x228x150
---------------------------
OK
---------------------------

##### Share on other sites
Might I ask why you're storing a void pointer version of the returned handle when you can store the actual value (as HWND)?
What's actually happening (what does happen and what doesn't)?
Have you stepped through the program with the debugger and checked values?
Is Util::WndProc in a class or namespace?
If it's in a class is it static?
How do you know that CreateWindowEx() returning an invalid handle?

Quote:
 If you think it's the that my window class is a WNDCLASSA and I've using the Extended version of CreateWindow, then I'm afraid I have to proof you wrong, this is a very valid thing to do. Not to mention, I've tried every combination.:P

Jumping to the defensive before anybody has even said anything seems quite rude and your statement also gives off the feeling that you think you're smarter than us.

Edit: With the above post, are you trying to center the window on the screen?

##### Share on other sites
Use a log file, never rely on MessageBox.

I have had many occasions when the messagebox never gets displayed.
Or at least use NULL for hwnd.

My gut feeling is that either,

1, your classname is getting screwed so your winproc never gets called
2, you've got an ordering problem

you call your createwindow, then set size, shape, style etc.
This will be fine as long as you have sensible default values, could be you have trash instead.

When you get to the bottom of it, post a message, this is interesting.

Stainless

##### Share on other sites
Quote:
 Original post by Programmer16Might I ask why you're storing a void pointer version of the returned handle when you can store the actual value (as HWND)?What's actually happening?Have you stepped through the program with the debugger and checked values?Is Util::WndProc in a class or namespace?If it's in a class is it static?

All my classes and functions are in the OOWin32 namespace, which has various sub namespaces (Util is one of them), so Util::WndProc is a normal function in the Util namespace.

I would never try to use a member function as a function pointer, unless it's through a functor (function object,which Win32 doesn't accept, or even knows).^_^

The reason why I am I storing the handle as a void pointer is because I wanted to prevent the inclusion of windows.h in the header file, and I didn't want to give out my pimpl_ pointer. And a HWND is a pointer anyway (it's a typedef for HWND__*, which is an empty struct, save for a char if I remember correctly).

Quote:
Quote:
 If you think it's the that my window class is a WNDCLASSA and I've using the Extended version of CreateWindow, then I'm afraid I have to proof you wrong, this is a very valid thing to do. Not to mention, I've tried every combination.:P

Jumping to the defensive before anybody has even said anything seems quite rude and your statement also gives off the feeling that you think you're smarter than us.

It wasn't meant as being defensive, more as pro-active (sorry if it was percieved(sp) as offensive).
I've seen a lot of threads through my googling which in the end got stuck on a debate if it's alright or not to mix those functions, I was merely trying to prevent that.

##### Share on other sites

Quote:
 Original post by Anonymous PosterUse a log file, never rely on MessageBox. I have had many occasions when the messagebox never gets displayed.

In the WndProc I'm currently using, I've set a MessageBox, a break point and 2 asserts (forgot which way the logic was, so I did assert(0); assert(1); ^_^'), and _none_ of them get called.

Quote:
 Or at least use NULL for hwnd.

Could have done that, but NULL is the same as 0 anyway.
Most of the time I use NULL anyway, the this->handle = 0 was done quick, in case something was really going wrong.

Quote:
 My gut feeling is that either,1, your classname is getting screwed so your winproc never gets called

Quick question, does the classname have to be exactly the same, as in the same memory address?
Since if I remember correctly, the c_str() creates a copy.

Quote:
 2, you've got an ordering problemyou call your createwindow, then set size, shape, style etc. This will be fine as long as you have sensible default values, could be you have trash instead.

createwindow just creates the abstract window class (an constructable class representing a window), the real window (as in using the Win32 API's) is created when needed (such as when it's set to visible, and the Win32 window hasn't been created yet) through the initialize function.

Quote:
 When you get to the bottom of it, post a message, this is interesting.

As find I.;)

##### Share on other sites
Quote:
Original post by mldaalder
Quote:
 Original post by Programmer16Might I ask why you're storing a void pointer version of the returned handle when you can store the actual value (as HWND)?What's actually happening?Have you stepped through the program with the debugger and checked values?Is Util::WndProc in a class or namespace?If it's in a class is it static?

All my classes and functions are in the OOWin32 namespace, which has various sub namespaces (Util is one of them), so Util::WndProc is a normal function in the Util namespace.

I would never try to use a member function as a function pointer, unless it's through a functor (function object,which Win32 doesn't accept, or even knows).^_^

The reason why I am I storing the handle as a void pointer is because I wanted to prevent the inclusion of windows.h in the header file, and I didn't want to give out my pimpl_ pointer. And a HWND is a pointer anyway (it's a typedef for HWND__*, which is an empty struct, save for a char if I remember correctly).

Quote:
Quote:
 If you think it's the that my window class is a WNDCLASSA and I've using the Extended version of CreateWindow, then I'm afraid I have to proof you wrong, this is a very valid thing to do. Not to mention, I've tried every combination.:P

Jumping to the defensive before anybody has even said anything seems quite rude and your statement also gives off the feeling that you think you're smarter than us.

It wasn't meant as being defensive, more as pro-active (sorry if it was percieved(sp) as offensive).
I've seen a lot of threads through my googling which in the end got stuck on a debate if it's alright or not to mix those functions, I was merely trying to prevent that.

That's understandable, though I don't understand why you would want to avoid including windows.h for a window's wrapper.

But, what about my other questions?
What does the application actually do?
Does it compile?
Does it run to a certain point and stop?
Does it open the window and close?
Have you stepped through and double checked the values of different things?
Have you tried "running to" your window's procedure?

Btw, no the classname doesn't have to be the same address memory, but I'm pretty sure c_str() doesn't return a copy (not positive, you might want to check into it.)

##### Share on other sites
Quote:
 Original post by Anonymous PosterMy gut feeling is that either,1, your classname is getting screwed so your winproc never gets called2, you've got an ordering problemWhen you get to the bottom of it, post a message, this is interesting.Stainless

I agree with Stainless. But you seem to know what you're doing. The following is a list of things I would try, in order of increasing desperation. I'm sure you've already tried some of these things. I'm just thinking out loud because these are the kinds of bumps that break my blocks when I've got a bug that makes no sense.

First, step through *every* line of code no matter how sure you are that there's no problem with it and visually verify that variables hold the values you expect and operations are actually doing what they're supposed to do. Oh, and reboot/clean/rebuild first :)

It's probable that your WndProc is never being called because your window is never being created - thus the INVALID_HANDLE from CreateWindow. So that makes sense to me. It seems like the problem must be either in your WNDCLASS data, the parameters to RegisterClass, or the parameters to CreateWindow. Less likely, but still possible, is that something weird is going on because you're forcing the ansi versions. Or maybe there is some other factor that we (on the forum) can't see (e.g. custom memory manager problems, dlls, threads, etc). You could also try the "errno" global (stddef.h, C standard) and see if there's anything useful in there.

If stepping through code doesn't work, then it's time to get dirty... replace variable use in the RegisterClass/CreateWindow sequence with a constant wherever possible. For example, hard-code the classname, the window rect, the title, etc etc. If it still doesn't work, then pull all of this code out into a new project that has one main or WinMain function, and paste the code in serially to that one big function in the order you think it normally executes. Replace function calls with blocks of code, replace member variables with globals, replace constants with literals. Then start removing your code until it becomes a "hello world" win32 app. Somewhere along the way it should start working, and you'll know that whatever you just changed was the problem. If it still doesn't work then something is wrong with your compiler or computer :p

OH, also, if you're using any version MSVC, you can use the meta-variable "@err" in the watch window to monitor the value of GetLastError as you step through code.

EDIT: Also, if your header file redefines Win32 types and your CPP file uses the real Win32 types, then make sure that they're EXACTLY the same. As a sledgehammer test, just change all the code to include windows.h.

##### Share on other sites
Quote:
 Original post by Programmer16That's understandable, though I don't understand why you would want to avoid including windows.h for a window's wrapper.

May seem strange, but at the system I'm developing on at work (I'm an intern, who has got to program a tray tool in C++ in a company that only works with Java and webservices), the build time sky rockets for every windows.h inclusion, so I'm trying to limit it as much as possible.

Quote:
 But, what about my other questions?

-What does the application actually do?
The intended purpose is to display a window (for now).

-Does it compile?
Yes.

-Does it run to a certain point and stop?
Yes, it goes up until the CreateWindowEx. Which returns 0, but does not set the LastError, because the handle is invalid, the window instance is removed by the WindowManager. After which the setVisible returns and the program enters the message loop, because there are no windows, so no events, the message loop doesn't loop and the program exists.

-Does it open the window and close?
No, it never creates a window.

-Have you stepped through and double checked the values of different things?
-Have you tried "running to" your window's procedure?
I have stepped several times through the entire program, and to my knowledge, it all goes right up until the CreateWindowEx.

Quote:
 Btw, no the classname doesn't have to be the same address memory, but I'm pretty sure c_str() doesn't return a copy (not positive, you might want to check into it.)

I'm expecting a couple of books on the STL soon.

##### Share on other sites
Quote:
 Original post by JaymarI agree with Stainless. But you seem to know what you're doing.

Thanks for the compliment.

Quote:
 The following is a list of things I would try, in order of increasing desperation. I'm sure you've already tried some of these things. I'm just thinking out loud because these are the kinds of bumps that break my blocks when I've got a bug that makes no sense.

Quote:
 First, step through *every* line of code no matter how sure you are that there's no problem with it and visually verify that variables hold the values you expect and operations are actually doing what they're supposed to do. Oh, and reboot/clean/rebuild first :)

I'll try that again, but I think I'll try and create a reference program that simply creates a window, so no class stuff. For all I know, some values I see as correct might not be.

Quote:
 It's probable that your WndProc is never being called because your window is never being created - thus the INVALID_HANDLE from CreateWindow. So that makes sense to me. It seems like the problem must be either in your WNDCLASS data, the parameters to RegisterClass, or the parameters to CreateWindow. Less likely, but still possible, is that something weird is going on because you're forcing the ansi versions. Or maybe there is some other factor that we (on the forum) can't see (e.g. custom memory manager problems, dlls, threads, etc). You could also try the "errno" global (stddef.h, C standard) and see if there's anything useful in there.

I hadn't thought of that, I prefer to use C++ (or Python).

Quote:
 If stepping through code doesn't work, then it's time to get dirty... replace variable use in the RegisterClass/CreateWindow sequence with a constant wherever possible. For example, hard-code the classname, the window rect, the title, etc etc. If it still doesn't work, then pull all of this code out into a new project that has one main or WinMain function, and paste the code in serially to that one big function in the order you think it normally executes. Replace function calls with blocks of code, replace member variables with globals, replace constants with literals. Then start removing your code until it becomes a "hello world" win32 app. Somewhere along the way it should start working, and you'll know that whatever you just changed was the problem. If it still doesn't work then something is wrong with your compiler or computer :p

So the reference program I spoke of.
The compiler is VS2005 Professional (got it at a student discount).

Quote:
 OH, also, if you're using any version MSVC, you can use the meta-variable "@err" in the watch window to monitor the value of GetLastError as you step through code.

Now this is intteresting.

Quote:
 EDIT: Also, if your header file redefines Win32 types and your CPP file uses the real Win32 types, then make sure that they're EXACTLY the same. As a sledgehammer test, just change all the code to include windows.h.

I don't redefine them, I just use their "normal" counterparts.

##### Share on other sites
Quote:
Original post by mldaalder
Quote:
 OH, also, if you're using any version MSVC, you can use the meta-variable "@err" in the watch window to monitor the value of GetLastError as you step through code.

Now this is intteresting.

There's a list of these meta-variables in this thread. The "@clk" variable is really useful too :)

##### Share on other sites
Many thanks, should help me improve my debugging (and coding) skills.

##### Share on other sites
Well, the only thing left that I can think of trying is replacing your call to CreateWindowEx() with some default values:
// Note that you'll have to change the WNDCLASS lpszClassName to "OOWin32Window" as well.HWND hWnd = CreateWindowExA(					0,							// Extended Style For The Window					"OOWin32Window",					// Class Name					"This is a test window",						// Window Title					WS_OVERLAPPEDWINDOW |							// Defined Window Style					WS_CLIPSIBLINGS |					// Required Window Style					WS_CLIPCHILDREN,					// Required Window Style					0, 0,	// Window Position					800,	// Calculate Window Width					600,	// Calculate Window Height					NULL,								// No Parent Window					NULL,								// No Menu					hInstance,							// Instance					NULL);								// Window Long, used to pass along for user data.

Then work backwards from there. Replace '0, 0' with you position, then 800 and 600 with your width and height, then title, classname, style, and styleex.

Edit: also, are you sure that you have a correct hInstance value?
Edit2: Nevermind, you're setting hInstance to GetModuleHandle(0) so it should be fine.

##### Share on other sites
What does WindowManager::createWindow look like? You haven't shown that code as far as I can see.

##### Share on other sites
createWindow doesn't do anything exotic, in fact, the only Win32 api calls WindowManager has, are related to the application message pump and the relaying to the windows.

The code for createWindow:
Window* WindowManager::createWindow(){	return Util::createWindowOfType<Window>();}

And the helper function:
template<typename WindowClass> WindowClass* createWindowOfType(){	BOOST_STATIC_ASSERT((boost::is_convertible<WindowClass, Window>::value));	WindowClass* win = new WindowClass;	windows.push_back(reinterpret_cast<Window*>(win));	return win;}

I was a bit busy last night to do anything with this, so I'm going to create the reference implementation and go through this again now.

##### Share on other sites
It would so far appear that my extended style is the cause of my problems.

Somehow.

If I replace it with 0, then all is fine.

The extended style I had was: WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, and MSDN doesn't say anything about possible problems with either one.

Next mystery for me to solve:
I now have an unresponsive window with what appears like a failed attempt at converting ASCII characters to Unicode.

[EDIT] About the messed up title bar, when I replace my WndProc to DefWindowProc (which my WndProc calls anyway) then the title bar is alright.

##### Share on other sites
Found the cause of the problem, I was storing my dwstyle and dwExstyle as long, instead of the used unsigned long.

This seemed to be the cause of the problems.

Now I just have an unresponsive window, which may indicate either an endless loop, or a faulty WndProc.XD

I think the former.

It's unresponsive as in no content (just frame and title bar), mouse cursor changes to the hourglass, and it doesn't always focus correctly.

##### Share on other sites
Quote:
 Original post by mldaalderFound the cause of the problem, I was storing my dwstyle and dwExstyle as long, instead of the used unsigned long.This seemed to be the cause of the problems.Now I just have an unresponsive window, which may indicate either an endless loop, or a faulty WndProc.XDI think the former.It's unresponsive as in no content (just frame and title bar), mouse cursor changes to the hourglass, and it doesn't always focus correctly.

That could be the result of DefWindowProc() being called more than once per message or a infinite loop (obviously there could be other causes, but those are the only two that have ever caused it for me.)