问题
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