This is probably not the highest quality answer; suggestions for improvement welcome.
You are correct in assuming that the value of a HWND never changes while the window that the HWND points to remains alive.
What I am guessing is that you have written code like this:
LRESULT CALLBACK wndproc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HWND button;
switch (uMsg) {
case WM_CREATE:
button = CreateWindowEx(...);
break;
case WM_COMMAND:
if (lParam == (LPARAM) button)
/* button was clicked; do something */;
}
return DefWindowProc(...);
}
and wondering why it doesn't work, but changing
HWND button;
to
static HWND button;
fixes it.
This is not a property of HWNDs. Nothing about the code failing is because the value of the HWND has changed. In fact, this has nothing to do with Windows at all, and everything to do with C.
The reason why the code doesn't work is that the variable button
is created fresh each time the wndproc()
function is called. See, a window procedure is called many times, once for each message that a window ever receives throughout the execution of your program. Each time, you get a brand new button
variable, and the value that the button
variable had in previous calls is lost. The pointer is still there, but it's not stored in any variable or any other memory location! The window hasn't been destroyed. You just can't get to it through normal means anymore.
What the static
does is tell C that you want the variable to stay around through every function call. So now every call to your window procedure has the same button
, and that pointer value isn't lost anymore.
It's a quick fix, and it doesn't really scale well to very large projects. In those cases, structures containing the window handles, (maybe) global variables, or use of GWLP_USERDATA
or other cbWndExtra
bytes are better. I guess a better question is why this quick fix keeps getting suggested as the solution to other peoples's similar problems here on Stack Overflow (or at least why it is a quick fix isn't explained), but that's something we have to think about as a community.
Just remember that by default, in most languages (not just C and C++!), a function's local variables only exist for the duration of each individual function call.