MrEff

I'm new to using the Windows API, and I can't figure out where I should declare all my variables. In a console application they would all go at the beginning of main(), but if I put them in WinMain() they will be out of scope in WndProc where all the action is. The tutorials I've read seem to solve this problem by simply declaring all variables at global scope...but momma always told me that global variables = bad. Is there a clean solution that I'm missing

Re: Visual C++ General Declaration of Variables with Win API

crescens2k

It depends on where you want the variables to be used. If they are just short lifespan in the Windows procedure then just declaring them in there is fine, examples of this are the PAINTSTRUCT and HDC variables when handling the WM_PAINT message. If you want to save the state of a window however there is another way of doing it.

Look in the WNDCLASS(EX) structure and you will see cbWndExtra and cbClsExtra. These are used to tell CreateWindow how much extra memory in the Window or Window Class you want. You can then use this extra memory by using the GetWindowLongPtr function with a positive value for nIndex.

A good way of doing this is to create a structure on windows initialisation and put it into the extra memory. If you require a lot of data then having a lot of extra memory is not a good idea, so in this case set it to 4 bytes (8 on x64) and create a structure on the heap and then put a pointer to it in the extra memory. You can then use the WM_DESTROY message to get the pointer and free the memory.