Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is moving a window with SetWindowPos the 'normal way' to do?

Tags:

windows

winapi

I am wondering if, in order to move a (ms-windows-)window with the Win32 API 20 px to the right and 40 px downwards, the following function call would be how to do it:

SetWindowPos(
  /* hWnd             */  hChildDlg2, 
  /* hWndInsertAfter  */ (HWND) -1,
  /* X                */ 20,
  /* Y                */ 40,
  /* cx               */ -1,
  /* cy               */ -1,
  /* uFlags           */  SWP_NOSIZE |  // Ignore cx, cy
                          SWP_NOZORDER  // and hWndInsertAfter
);

I ask because it seems to me that there could be a function only taking a HWND and an x and y as parameters.

like image 331
René Nyffenegger Avatar asked Jan 08 '11 01:01

René Nyffenegger


2 Answers

Yes, that's pretty much how it's done. You should prefer to use SetWindowPos() since it gives you quite a bit of control over how the window should be moved/resized.

I typically use it like this (part of a small framework I wrote):

// Window member function
void Window::Move(int x, int y)
{
    if(hwnd != 0)
    {
        ::SetWindowPos(hwnd, 0, x, y, 0, 0, 
            SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
    }
}

There's also a MoveWindow() function that does pretty much the same thing. With the SetWindowPos() function available, it's now more of a convenience function than anything else.

like image 80
In silico Avatar answered Sep 19 '22 16:09

In silico


Yes, this is the normal way and the window will get a WM_WINDOWPOSCHANGING message (with the parameters that changed) There is also the older MoveWindow but it is less flexible and actually forces you to set the size.

To properly save and restore window sizes you should use GetWindowPlacement and SetWindowPlacement respectively.

like image 44
Anders Avatar answered Sep 18 '22 16:09

Anders