微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将C#Windows窗体置于另一个窗口中

我希望我的表单启动并在相对于调用表单时处于活动状态的窗口的中心打开.假设Firefox处于活动状态并显示表单,我希望我的表单显示在firefox窗口的“中心”.

我认为我可以通过使用user32.dll中的SetwindowPos来实现这一点,但我是
不太确定是否有更简单的方法.

我已经玩过SetwindowPos并且发现我可以轻松地将窗口放在整个屏幕上,但是我不太确定我应该在哪里开始将它相对于另一个窗口居中.

基本上,我需要:

>抓窗位置/大小
>做数学计算,找到中心的坐标减去我的表格大小到准备
>显示我的表格并使用设置窗口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  
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐