Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

winforms

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.

like image 537
Zach Johnson Avatar asked Feb 18 '10 22:02

Zach Johnson


2 Answers

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));
}
like image 125
Zach Johnson Avatar answered Sep 23 '22 04:09

Zach Johnson


Don't do this.

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

like image 39
SLaks Avatar answered Sep 21 '22 04:09

SLaks