Zach Johnson
Zach Johnson

Reputation: 24232

Make window always stay on top of ANOTHER window that already stays on top?

How can I make a window always stay on top of another window that already always stays on top? Not that it has to stay on top of all other windows, I just need it to stay on top of a particular window.

Upvotes: 9

Views: 9351

Answers (2)

Zach Johnson
Zach Johnson

Reputation: 24232

Thanks to SLaks's answer and some of the comments on it, I was able to figure out how set a child-parent relationship between my forms. I couldn't use Form.Show(owner), because the form that I wanted to stay in front was shown before the other form. I used Reflector to examine the code behind Form.Show(owner) and discovered that behind the scenes, it all resolves down to SetWindowLong in the Windows API.

LONG SetWindowLong(      
    HWND hWnd,
    int nIndex,
    LONG dwNewLong
);

Form.Show(owner) calls SetWindowLong with an nIndex of -8. The MSDN online documentation won't tell you about it, but according to Winuser.h one of the constants available for nIndex is GWL_HWNDPARENT, which has a value of -8. Once I connected these dots, the problem was quite easy to solve.

This following is how to set the window's parent, even if it is already shown:

using System.Runtime.InteropServices;

[DllImport("user32.dll")]
public static extern int SetWindowLong(HandleRef hWnd, int nIndex, HandleRef dwNewLong);

public static void SetOwner(IWin32Window child, IWin32Window owner)
{
    NativeMethods.SetWindowLong(
        new HandleRef(child, child.Handle), 
        -8, // GWL_HWNDPARENT
        new HandleRef(owner, owner.Handle));
}

Upvotes: 17

SLaks
SLaks

Reputation: 888283

Don't do this.

That said, you should be able to do it by making your window a child of the other one.

Upvotes: 2

Related Questions