加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:17:55 所属栏目:百科 来源:网络整理
导读:我希望我的表单启动并在相对于调用表单时处于活动状态的窗口的中心打开.假设Firefox处于活动状态并显示表单,我希望我的表单显示在firefox窗口的“中心”. 我认为我可以通过使用user32.dll中的SetWindowPos来实现这一点,但我是 不太确定是否有更简单的方法.
我希望我的表单启动并在相对于调用表单时处于活动状态的窗口的中心打开.假设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  
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读