在另一个窗口内居中放置C#Windows窗体

| 我希望我的表单能够启动并相对于调用表单时处于活动状态的窗口在中心打开。假设Firefox是活动的并且我显示了表单,我希望将表单显示在firefox窗口的“中心”中。 我认为可以实现此目的的一种方法是使用user32.dll中的SetWindowPos,但是我 不太确定是否有更简单的方法。 我已经玩过SetWindowPos了,发现我可以轻松地使窗口在整个屏幕上居中,但是我不太确定我应该在哪个位置开始相对于另一个窗口居中。 基本上,我将需要: 抓窗位置/大小 做数学运算以找到中心的坐标减去我准备的表单大小 显示我的表单并使用set window pos正确放置它? 注意:CenterParent不适用于此功能,它似乎仅适用于另一个Form控件。我想将其用于其他窗口,例如Firefox。     
已邀请:
        如果要使新窗口相对于父窗口居中,则可以将子窗体的“ 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  
}
    

要回复问题请先登录注册