0

I am currently writing a class in c++ to code for a window. When I create the window with CreateWindow(...), it, of course, returns a handle to that window. However, when the WNDPROC runs it also gives a copy of that handle. So, should I store that original handle from the CreateWindow(...) as a class variable or is that bad practice? My first instinct was to just store it in case I need to access it from outside the class (the WNDPROC is inside the class). However, I noticed that in the code samples that I have studied this is not generally done. It seems that normally a handle to the instance is stored but the HWND is only accessed within the WNDPROC. I am correct in this assumption? And if so, is there any reason, or is it just convention?

  • 5
    it's fine to store it, you are eventually going to need it when you perform operations on the window outside the wndproc. – Andy Mar 05 '21 at 01:26
  • 3
    "*the `WNDPROC` is inside the class*" It can't be a member function, and static functions can't access non-static members, so there is no contradiction or overlap between storing the `HWND` as a data member of individual objects, *and* having it passed as an argument to the static `WndProc`. – dxiv Mar 05 '21 at 01:28
  • Thank you! I just wanted to make sure I didn't break something accidently. – Juanita Lopez Mar 05 '21 at 01:30
  • 3
    @dxiv in fact you often want a map to convert from `HWND` to objects, so that the `WndProc` can route messages to the proper object. – Mark Ransom Mar 05 '21 at 01:34
  • @MarkRansom while this (use map hwnd -> object) is possible, better bind object to hwnd via `GWLP_USERDATA` or another private index from extra window memory – RbMm Mar 05 '21 at 09:39
  • @RbMm yes, that's one way to implement such a map. But it does have the disadvantage that if your window outlives your C++ object, you could get a dangling pointer. – Mark Ransom Mar 05 '21 at 16:42
  • @MarkRansom - *you could get a dangling pointer* - this already depend from implementation. i for example always use reference counting on object connected to *HWND*. when do this connect - use *AddRef* on object and on disconnect (say on `WM_NCDESTROY` ) call *Release*. anyway save *hwnd* inside object always ok – RbMm Mar 05 '21 at 16:55
  • @RbMm Interesting that you recommend `GWLP_USERDATA` for this, given that you are the author if [this excellent, yet unanswered question](https://stackoverflow.com/questions/41521809/who-is-owner-of-gwlp-userdata-cell). I would prefer *extra window memory* for this. (Although this is off-topic anyway for this question, probably...) – dialer Mar 05 '21 at 20:59
  • @dialer - despite no definite answer who can use `GWLP_USERDATA`, now i think that faster code which implement window class. if another code need subclass window, need use `SetWindowSubclass` – RbMm Mar 05 '21 at 21:09

0 Answers0