我希望我的表单在相对于调用我的表单时处于活动状态的窗口的中心启动并打开。假设如果 Firefox 处于活动状态并且我显示表单,我希望我的表单显示在 Firefox 窗口的“中心”。
我认为实现此目的的一种方法是使用 user32.dll 中的 SetWindowPos,但我
不太确定是否有更简单的方法。
我已经尝试过 SetWindowPos 并发现我可以轻松地将窗口在整个屏幕上居中,但我不太确定应该从哪里开始将其相对于另一个窗口居中。
基本上,我需要:
- 抓取窗口位置/大小
- 进行数学计算,找到中心坐标减去要准备的表格大小
- 显示我的表单并使用设置窗口位置来正确定位它?
注意: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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)