Sign in to follow this  

C++ Passing variables to the Window Procedure

Recommended Posts

Without creating global variables, is there a way to pass variables to the WindowProcedure that handles the messages? For example, if I create a variable and initialize it in WinMain, is there any way to use it in my WindowProcedure? What I am doing is this. I have a class called Map. I also have a class called Texture and Window. When I create Texture and Window, certain variables are created such as texWidth, texHeight, windowWidth, and WindowHeight inside of the class. In my Window Procedure, I need to use those variables held inside of Texture and Window for some function calls. Is there any way to do this easily? I would really like to keep it simple and try to avoid global variables if possible.

Share this post

Link to post
Share on other sites
Same way you would support OO in your window code.

Personally, I do it this way:
1) When I'm setting up the WNDCLASSEX structure for my window, I do this:
windowClass.cbWndExtra = sizeof(Window*);

2) I register my window class (RegisterClassEx).
3) When creating the window using CreateWindowEx, I pass the pointer to the Window class as the last parameter.
4) In my static Window function, I process the WM_CREATE message like this (I save the pointer to window class in the space that window allocated for me):
CREATESTRUCT * cs = reinterpret_cast< CREATESTRUCT * >(lParam);
Window * window = reinterpret_cast< Window * >(cs->lpCreateParams);
assert(window != 0);
SetWindowLongPtr(handle, GWLP_USERDATA, reinterpret_cast< LONG_PTR >(window));

From now on, the window actually knows which object of (my own) Window class represents it.
5) Every time I need to process the message and get the Window pointer from window handle, I can do this:
Window * window = reinterpret_cast< Window * >(GetWindowLongPtr(handle, GWLP_USERDATA));

It may sound as a complex thing, but it isn't really. :)

Share this post

Link to post
Share on other sites
Yea, I was looking into that, but I really would like something more simple. I'm talking to a guru right now on msn and I think he has a good solution. I'll get back to you all.

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