在另一个窗口中居中一个 C# Windows 窗体 [英] Center a C# Windows Form inside another window

查看:32
本文介绍了在另一个窗口中居中一个 C# Windows 窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want my form to start up and open in the center relative to window that was active when my form was called. Say if Firefox was active and I display the form, I'd like my form to be shown in the "center" of the firefox window.

我认为实现这一目标的一种方法是使用 user32.dll 中的 SetWindowPos,但我不太确定是否有更简单的方法.

I think one way I can achieve this is by using SetWindowPos from user32.dll, but I'm not too sure if there is an easier way.

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

I have already played around with SetWindowPos and found that I can easily center my window on the whole screen, but I'm not too sure about where I should start to work on centering it relative to another window.

基本上,我需要:

  1. 抓取窗口位置/大小
  2. 计算中心坐标减去要准备的表单大小
  3. 显示我的表单并使用 set window pos 来正确定位它?

注意:CenterParent 对此不起作用,它似乎只适用于另一个 Form 控件.我想在其他窗口中使用它,例如 Firefox.

Note: CenterParent will not work for this, it seems to only work for another Form control. I want to use this with other windows, like Firefox for example.

推荐答案

如果你想让新窗口相对于父窗口居中,那么你可以将子窗体的StartPosition"设置为CenterParent".如果您想让新窗口相对于其他窗口居中,那么我认为您已经处理了 Windows API.

If you want center the new window relative to parent window, then you can set the "StartPosition" of the child form to "CenterParent". If you want center the new window relative to some other window then i think you have handle the 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  
}

这篇关于在另一个窗口中居中一个 C# Windows 窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆