How to make a modeless dialog always on top within

2019-02-27 23:56发布

问题:

I have a modeless popup dialog in my app. I want to make it topmost only within the app it belongs to, not always topmost on the desktop.

I have tried to set the first parameter to wndTopMost, but this way the dialog will remain on top on the desktop, which is very bad user experience.

I have also tried wndNoTopMost with SWP_NOZORDER parameter, but this only put the dialog in front when its displayed. If I move another dialog/window to the dialog location, the dialog will be buried under the new dialog/window.

I am currently using the SetWindowPos in the OnInitDialog();

   SetWindowPos(&wndNoTopMost
    , myRect.left
    , myRect.top
    , myRect.Width()
    , myRect.Height()
    , SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOZORDER
    );

回答1:

Yes HWND_TOPMOST is a very bad user experience, so I will commend you for not taking the easy way out and trying to flip this switch.

The key to getting a dialog to appear on top of other windows is setting its owner. (Note that in Win32, an owner is distinct from a parent window, although the terms are often confusing.) All dialogs have an owner, and dialogs always stay on top of their owner.

So when you create the modeless dialog (e.g. using the CreateDialog function), make sure to specify the handle to your application's main window as its owner. Confusingly, the parameter is named hwndParent, but it actually specifies the owner window.