SetWindowPos/MoveWindow persist issue

4.3k views Asked by At

I am using SetWindowPos and MoveWindow to resize and center windows. It works fine, but on several windows like Windows Media Player or Control Panel, when you close the window and open it again, the new resizing/moving is not reflected. When I resize manually, the changes are reflected the next time I open the window. Even if I call UpdateWindow, the changes don't reflect. Is there something I need to send the window so the changes get saved? Would RedrawWindow help? Thanks?

1

There are 1 answers

4
Cody Gray - on strike On BEST ANSWER

You should be using the GetWindowPlacement and SetWindowPlacement functions instead to retrieve and alter the restored, minimized, and maximized positions of a window. This ensures that the window sizes are properly saved by the application so that they can be restored on the next launch.

Since you're using C#, you'll need to P/Invoke these functions from the Windows API:

const int SW_HIDE = 0;
const int SW_SHOWNORMAL = 1;
const int SW_SHOWMINIMIZED = 2;
const int SW_SHOWMAXIMIZED = 3;

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);

[StructLayout(LayoutKind.Sequential)]
struct RECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

[StructLayout(LayoutKind.Sequential)]
struct WINDOWPLACEMENT
{
    public int length;
    public int flags;
    public int showCmd;
    public Point ptMinPosition;
    public Point ptMaxPosition;
    public RECT rcNormalPosition;
}