在另一个窗口中居中显示C# Windows表单

4
我希望我的表单启动并在相对于调用表单时处于活动状态的窗口中心打开。例如,如果Firefox处于活动状态并且我显示表单,则希望我的表单显示在Firefox窗口的“中心”。
我认为我可以使用user32.dll中的SetWindowPos来实现这一点,但我不确定是否有更简单的方法。
我已经尝试了SetWindowPos并发现我可以轻松地将我的窗口居中于整个屏幕,但我不太确定应该从哪里开始居中相对于另一个窗口。
基本上,我需要:
1.获取窗口位置/大小 2.计算出中心坐标减去我的表单大小以准备 3.显示我的表单并使用set window pos来正确定位它?
注意:CenterParent无法起作用,它似乎只适用于另一个Form控件。我想与其他窗口一起使用,例如Firefox。
1个回答

2

如果你想将新窗口相对于父窗口居中,那么你可以将子窗体的“StartPosition”设置为“CenterParent”。如果你想将新窗口相对于其他窗口居中,则需要处理Windows API。

[DllImport("user32.dll")]  
static extern IntPtr GetForegroundWindow();  


private IntPtr GetActiveWindow()  
{  
    IntPtr handle = IntPtr.Zero;  
    return GetForegroundWindow();  
}

Then get the window position with GetWindowRect.

[DllImport("user32.dll")]  
[return: MarshalAs(UnmanagedType.Bool)]  
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);  

[StructLayout(LayoutKind.Sequential)]  
public struct RECT  
{
    public int Left;        // x position of upper-left corner  
    public int Top;         // y position of upper-left corner  
    public int Right;       // x position of lower-right corner  
    public int Bottom;      // y position of lower-right corner  
}

@Steven Colgrove - 我认为你需要使用user32.dll来获取当前活动窗口的位置。如果你需要相关代码,我可以提供给你。 :) - Bibhu
我认为他的意思不是将一个窗口居中于父窗口,而是将任意窗口居中。 - Steve Wellens
Bibhu,我很想要一个例子。我不太擅长使用这样的外部调用。 - cronzik
非常感谢这个。如果我有任何补充,可以让我进入窗口中心,我会将它们粘贴回来:D - cronzik
@aadster - 当然没问题 "aadster",我已经更新了答案,同时请查看以下链接 http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/4af7fa88-affd-4ca2-ba0a-9ee07e61d602/ - Bibhu
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接