我如何使用SetWindowPos?

时间:2015-07-07 14:41:48

标签: c# .net winforms

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的值应该是什么?

我想要做的是将把手放在屏幕的正面和中央。把它带到前面我知道怎么做我正在使用SetForegroundWindow(IntPtr hWnd);并且它工作正常。但是如何使用SetWindowPos强制置于屏幕中央?

1 个答案:

答案 0 :(得分:3)

在你掌握它之前,首先你必须知道是怎样的。这可以使用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);
        }
    }

}