What's the difference between SetWindowLongPtr(GWL_HWNDPARENT) and SetParent?

好久不见. 提交于 2021-02-10 17:36:23

问题


I need to create a watermark window(markHwnd) for some application windows on desktop, the watermark window style is:

            uint dwStyle = Win32API.WS_CLIPSIBLINGS |
                          Win32API.WS_CLIPCHILDREN |
                          Win32API.WS_POPUP;
            uint dwExStyle = Win32API.WS_EX_LAYERED |
                            Win32API.WS_EX_TRANSPARENT |
                            Win32API.WS_EX_NOACTIVATE |
                            Win32API.WS_EX_NOPARENTNOTIFY |
                            Win32API.WS_EX_TOOLWINDOW;
            markHwnd = Win32API.CreateWindowEx(dwExStyle, wndclassRegResult, ti.ToString(), dwStyle, 0, 0, 0, 0,IntPtr.Zero, IntPtr.Zero, wndclasshInstance, IntPtr.Zero);

Then I will set it to be an owned window of the application window(targetHwnd), there're two choices:

  • SetWindowLongPtr(markHwnd, (int)Win32API.GWL.GWL_HWNDPARENT, targetHwnd);
  • SetParent(markHwnd, targetHwnd);

Which one is suggested?


回答1:


The SetWindowLongPtr() documentation says:

Do not call SetWindowLongPtr with the GWLP_HWNDPARENT index to change the parent of a child window. Instead, use the SetParent function.

What this documentation is eluding to is that GWLP_HWNDPARENT actually changes the owner of a top-level window, not the parent of a child window. According to Raymond Chen:

A window can have a parent or an owner but not both

Now, a window can have a parent, or it can have an owner, or it can have neither, but it can never have both.

And he goes on to explain how CreateWindow/Ex() assigns an owner vs a parent depending on whether the new window has the WS_CHILD style or not.

The SetParent() documentation says:

For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. 

So, SetWindowLongPtr(GWLP_HWNDPARENT) is used to change the owner of a top-level window, and SetParent() is used to change the parent of a child window.



来源:https://stackoverflow.com/questions/63423266/whats-the-difference-between-setwindowlongptrgwl-hwndparent-and-setparent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!