如何使用 SetWindowPos 使窗口居中?

2024-04-24

我想做的是将手柄移到屏幕的前面和中央。把它放在前面我知道该怎么做我正在使用SetForegroundWindow(IntPtr hWnd);并且运行良好。但是如何使用 SetWindowPos 强制位于屏幕中央?

IntPtr handle = process.MainWindowHandle;
if (handle != IntPtr.Zero)
{
    SetWindowPos(handle, 0, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
}

那么,当我调用构造函数(例如 SetWindowPos)时,我应该给它什么?手柄很好,我知道它应该是什么。但是所有 resr 0,0,0,0,0,0 以及 SWP_NOZORDER 和 SWP_NOSIZE 的值应该是什么?


在将其居中之前,首先您必须知道如何big这是。这可以通过以下方式完成获取窗口矩形() http://www.pinvoke.net/default.aspx/user32.getwindowrectAPI。之后,只需考虑屏幕尺寸来计算中心位置即可:

public partial class Form1 : Form
{

    [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
    }

    private const int SWP_NOSIZE = 0x0001;
    private const int SWP_NOZORDER = 0x0004;
    private const int SWP_SHOWWINDOW = 0x0040;

    [DllImport("user32.dll", SetLastError=true)]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

    Process process;

    public Form1()
    {
        InitializeComponent();
        process = Process.GetProcessesByName("calc").FirstOrDefault();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (process == null)
            return;

        IntPtr handle = process.MainWindowHandle;
        if (handle != IntPtr.Zero)
        {
            RECT rct;
            GetWindowRect(handle, out rct);
            Rectangle screen = Screen.FromHandle(handle).Bounds;
            Point pt = new Point(screen.Left + screen.Width / 2 - (rct.Right - rct.Left) / 2, screen.Top + screen.Height / 2 - (rct.Bottom - rct.Top) / 2);
            SetWindowPos(handle, IntPtr.Zero, pt.X, pt.Y, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
        }
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 SetWindowPos 使窗口居中? 的相关文章

随机推荐