使窗口始终位于已经位于顶部的另一个窗口的顶部?

时间:2010-02-18 22:39:42

标签: c# .net winforms

如何让窗口始终位于另一个始终位于顶部的窗口之上?并不是说它必须保持在所有其他窗口的顶部,我只需要它保持在特定窗口的顶部。

2 个答案:

答案 0 :(得分:16)

感谢SLaks的回答和一些评论,我能够弄清楚如何设置我的表单之间的子父关系。我无法使用Form.Show(owner),因为我希望保留在前面的表单在之前显示另一种形式。我使用Reflector来检查Form.Show(owner)背后的代码,并发现在幕后,它们都在Windows API中解析为SetWindowLong

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

Form.Show(owner)使用nIndex -8调用SetWindowLong。 MSDN在线文档不会告诉您,但根据Winuser.h,nIndex可用的常量之一是GWL_HWNDPARENT,其值为-8。一旦我连接这些点,问题就很容易解决。

以下是如何设置窗口的父窗口,即使它已经显示:

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));
}

答案 1 :(得分:2)

Don't do this

那就是说,你应该能够让你的窗户成为另一个窗口的孩子。

相关问题