我如何使用SetWindowPos来居中窗口

本文关键字:窗口 SetWindowPos 何使用 | 更新日期: 2023-09-27 18:01:36

我想做的是把手柄放在屏幕的前面和中间。把它带到前面,我知道怎么做,我用的是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我应该给它什么?手柄很好,我知道它应该是什么。但是所有的值都是0,0,0,0,0,0 SWP_NOZORDER和SWP_NOSIZE的值应该是多少呢?

我如何使用SetWindowPos来居中窗口

在居中之前,首先你必须知道有多大。这可以通过GetWindowRect() API来完成。在那之后,它只是计算中心位置的问题,考虑到屏幕的大小:

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);
        }
    }
}