SetWindowPos function (winuser.h)
Changes the size, position, and Z order of a child, pop-up, or top-level window. These windows are ordered according to their appearance on the screen. The topmost window receives the highest rank and is the first window in the Z order.
Syntax
Parameters
A handle to the window.
A handle to the window to precede the positioned window in the Z order. This parameter must be a window handle or one of the following values.
Value | Meaning |
---|---|
HWND_BOTTOM (HWND)1 | Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows. |
HWND_NOTOPMOST (HWND)-2 | Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window. |
HWND_TOP (HWND)0 | Places the window at the top of the Z order. |
HWND_TOPMOST (HWND)-1 | Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated. |
В
For more information about how this parameter is used, see the following Remarks section.
The new position of the left side of the window, in client coordinates.
The new position of the top of the window, in client coordinates.
The new width of the window, in pixels.
The new height of the window, in pixels.
The window sizing and positioning flags. This parameter can be a combination of the following values.
Value | Meaning |
---|---|
SWP_ASYNCWINDOWPOS 0x4000 | If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. |
SWP_DEFERERASE 0x2000 | Prevents generation of the WM_SYNCPAINT message. |
SWP_DRAWFRAME 0x0020 | Draws a frame (defined in the window’s class description) around the window. |
SWP_FRAMECHANGED 0x0020 | Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window’s size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window’s size is being changed. |
SWP_HIDEWINDOW 0x0080 | Hides the window. |
SWP_NOACTIVATE 0x0010 | Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter). |
SWP_NOCOPYBITS 0x0100 | Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned. |
SWP_NOMOVE 0x0002 | Retains the current position (ignores X and Y parameters). |
SWP_NOOWNERZORDER 0x0200 | Does not change the owner window’s position in the Z order. |
SWP_NOREDRAW 0x0008 | Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing. |
SWP_NOREPOSITION 0x0200 | Same as the SWP_NOOWNERZORDER flag. |
SWP_NOSENDCHANGING 0x0400 | Prevents the window from receiving the WM_WINDOWPOSCHANGING message. |
SWP_NOSIZE 0x0001 | Retains the current size (ignores the cx and cy parameters). |
SWP_NOZORDER 0x0004 | Retains the current Z order (ignores the hWndInsertAfter parameter). |
SWP_SHOWWINDOW 0x0040 | Displays the window. |
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
As part of the Vista re-architecture, all services were moved off the interactive desktop into Session 0. hwnd and window manager operations are only effective inside a session and cross-session attempts to manipulate the hwnd will fail. For more information, see The Windows Vista Developer Story: Application Compatibility Cookbook.
If you have changed certain window data using SetWindowLong, you must call SetWindowPos for the changes to take effect. Use the following combination for uFlags: SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED .
A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window’s position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.
If neither the SWP_NOACTIVATE nor SWP_NOZORDER flag is specified (that is, when the application requests that a window be simultaneously activated and its position in the Z order changed), the value specified in hWndInsertAfter is used only in the following circumstances.
- Neither the HWND_TOPMOST nor HWND_NOTOPMOST flag is specified in hWndInsertAfter.
- The window identified by hWnd is not the active window.
An application cannot activate an inactive window without also bringing it to the top of the Z order. Applications can change an activated window’s position in the Z order without restrictions, or it can activate a window and then move it to the top of the topmost or non-topmost windows.
If a topmost window is repositioned to the bottom (HWND_BOTTOM) of the Z order or after any non-topmost window, it is no longer topmost. When a topmost window is made non-topmost, its owners and its owned windows are also made non-topmost windows.
A non-topmost window can own a topmost window, but the reverse cannot occur. Any window (for example, a dialog box) owned by a topmost window is itself made a topmost window, to ensure that all owned windows stay above their owner.
If an application is not in the foreground, and should be in the foreground, it must call the SetForegroundWindow function.
To use SetWindowPos to bring a window to the top, the process that owns the window must have SetForegroundWindow permission.
Console. Set Window Size(Int32, Int32) Метод
Определение
Устанавливает заданные значения высоты и ширины окна консоли. Sets the height and width of the console window to the specified values.
Параметры
Ширина окна консоли измеряется столбцами. The width of the console window measured in columns.
Высота окна консоли измеряется строками. The height of the console window measured in rows.
Исключения
width или height меньше или равно нулю. width or height is less than or equal to zero.
Сумма width и WindowLeft либо сумма height и WindowTop больше или равна MaxValue. width plus WindowLeft or height plus WindowTop is greater than or equal to MaxValue.
Значение параметра width или height больше ширины или высоты окна максимально возможной при текущем разрешении и шрифте консоли. width or height is greater than the largest possible window width or height for the current screen resolution and console font.
Пользователь не имеет разрешений на выполнение этого действия. The user does not have permission to perform this action.
Ошибка ввода/вывода. An I/O error occurred.
Текущая операционная система не является системой Windows. The current operating system is not Windows.
Примеры
В этом примере демонстрируется SetWindowSize метод, а WindowWidth также WindowHeight Свойства и. This example demonstrates the SetWindowSize method, and the WindowWidth and WindowHeight properties. Чтобы увидеть полный результат изменения размера окна консоли, необходимо выполнить пример. You must run the example to see the full effect of changing the console window size.
Пример сообщает размерам окна консоли, для которых задано значение 85 столбцов и 43 строк, а затем ожидает нажатия клавиши. The example reports the dimensions of a console window set to 85 columns and 43 rows, then waits for a key to be pressed. При нажатии любой клавиши размеры окна консоли увеличиваются вдвое, выводятся новые измерения, а в примере ожидается еще один нажатие клавиши. When any key is pressed, the dimensions of the console window are halved, the new dimensions are reported, and the example waits for another key press. Наконец, при нажатии любой клавиши окно консоли восстанавливается до исходных измерений, а пример завершается. Finally, when any key is pressed, the console window is restored to its original dimensions and the example terminates.
Set console window size on Windows
I know that there is a lot questions about how to set console size. But all found solutions are the same to my and my code doesn’t works for me.
Ok, so for setting console window size, I need two functions. They are SetConsoleScreenBufferSize() and SetConsoleWindowInfo(). First version of my function:
SetConsoleScreenBufferSize() will work not for all values. From documentation:
The specified width and height cannot be less than the width and height of the console screen buffer’s window
Lets try to get current window’s size and call our function. To get window size, I need GetConsoleScreenBufferInfo() function. main() test code:
In this case SetConsoleScreenBufferSize() works fine. Next function is SetConsoleWindowInfo() . This function will work in case:
The function fails if the specified window rectangle extends beyond the boundaries of the console screen buffer. This means that the Top and Left members of the lpConsoleWindow rectangle (or the calculated top and left coordinates, if bAbsolute is FALSE) cannot be less than zero. Similarly, the Bottom and Right members (or the calculated bottom and right coordinates) cannot be greater than (screen buffer height – 1 ) and (screen buffer width – 1 ), respectively. The function also fails if the Right member (or calculated right coordinate) is less than or equal to the Left member (or calculated left coordinate) or if the Bottom member (or calculated bottom coordinate) is less than or equal to the Top member (or calculated top coordinate).
In our case, the values of rectangle are the same (because Left and Top are zeroes) as values of info.srWindow rectangle after call of GetConsoleScreenBufferInfo() . But! SetConsoleWindowInfo() fails with next ::GetLastError()
If I swap calls of this two functions:
then I will have the same error.
So, how can I use SetConsoleScreenBufferSize() and SetConsoleWindowInfo() correctly ?
Setting window size on desktop for a Windows 10 UWP app
I’ve just started learning UWP app development on Windows 10 Pro using Visual Studio 2015 Community Edition. I tried to modify the C# version of the official «Hello, World!» sample by setting the Width and Height attributes of the Page tag in MainPage.xaml.
Interestingly, when I start the app, its size will be different. Moreover, if I resize its window and then restart it, the app seems to remember its previous window size.
Is it possible to force a UWP app to have a predefined window size, at least on desktop PCs?
3 Answers 3
Try setting PreferredLaunchViewSize in your MainPage ‘s constructor like this:
As @kol also pointed out, if you want any size smaller than the default 500×320, you will need to manually reset it:
You don’t really have control over the window size, and even if you will try to re-size it it may fail. I’ve asked the same question on MSDN forums and got the answer here:
BTW, here is the solution in your event handler «OnLaunched» or in your Event Handler «OnActivated» find:
And replace it with:
It is better if you place this code into the «OnActivated()» event handler as it will set your defined size when the app starts and when it becomes active after any interruptions.
In the «desiredSize» calculation, 800 is the width and 600 is the height. This calculation is needed, because the size is in DPI, so you have to convert it from pixels to DPI.
Also keep in mind that size cannot be smaller than «320×200».
Windows api set window size
Функция SetWindowPos изменяет размер, позицию и Z-последовательность дочернего, выскакивающего или верхнего уровня окна. Дочерние, выскакивающие и верхнего уровня окна размещаются по порядку согласно их появлению на экране. Самое верхнее окно принимает самый высокий ранг и становится первым окном в Z-последовательности.
HWND hWnd, // дескриптор окна
HWND hWndInsertAfter, // дескриптор порядка размещения
int x, // позиция по горизонтали
int y, // позиция по вертикали
int cx, // ширина
int cy, // высота
UINT uFlags // флажки позиционирования окна
[in] Дескриптор окна.
[in] Дескриптор окна, которое предшествует установленному окну в Z-последовательности. Этот параметр должен быть дескриптор окна или одним из следующих значений:
Значение
Предназначение
HWND_BOTTOM
Помещает окно внизу Z—последовательности. Если параметр hWnd идентифицирует самое верхнее окно, окно теряет свой статус самого верхнего и помещается внизу всех других окон.
HWND_NOTOPMOST
Помещает окно перед всеми не самыми верхними окнами (то есть позади всех самых верхних окон). Этот флажок не имеет никакого влияния, если окно — уже не самое верхнее окно.
HWND_TOP
Помещает окно наверху Z-последовательности.
HWND_TOPMOST
Помещает окно перед не самыми верхними окнами. Окно сохраняет свою самую верхнюю позицию даже тогда, когда оно теряет активность.
Для получения дополнительной информации о том, как использовать этот параметр, см. следующий раздел Замечания.
[in] Устанавливает новую позицию с левой стороны окна, в рабочих координатах.
[in] Устанавливает новую позицию верхней части окна, в рабочих координатах.
[in] Устанавливает новую ширину окна, в пикселях.
[in] Устанавливает новую высоту окна, в пикселях.
[in] Определяет флажки, устанавливающие размеры и позицию окна. Этот параметр может быть комбинацией следующих значений:
Значение
Предназначение
SWP_ASYNCWINDOWPOS
Если вызывающий поток и поток, который владеет окном, подключены к разным очередям ввода данных, система посылает запрос потоку, который владеет окном. Это не допускает блокирования работы вызывающего потока, в то время пока другие потоки обрабатывают запрос.
SWP_DEFERERASE
Препятствует созданию сообщения WM_SYNCPAINT .
SWP_DRAWFRAME
Выводит рамку (определенную в описании класса окна) вокруг окна.
SWP_FRAMECHANGED
Применяет новую установку стилей рамок, используя функцию SetWindowLong .
Отправляет сообщение WM_NCCALCSIZE окну, даже тогда, когда размер окна не изменяется. Если этот флажок не установлен, WM_NCCALCSIZE отправляется только тогда, когда размер окна изменяется.
SWP_HIDEWINDOW
Скрывает окно.
SWP_NOACTIVATE
Не активизирует окно. Если этот флажок не установлен, окно активизируется и перемещается в верхнюю часть или самой верхней, или не самой верхней группы (в зависимости от установки параметра hWndInsertAfter .)
SWP_NOCOPYBITS
Сбрасывает все содержание рабочей области. Если этот флажок не установлен, допустимое содержание рабочей области сохраняется и копируется обратно в рабочую область после того, как окно изменило размер или переустановлено.
SWP_NOMOVE
Сохраняет текущую позицию (игнорирует X и Y параметры).
SWP_NOOWNERZORDER
Не изменяет позицию окна владельца в Z—последовательности.
SWP_NOREDRAW
Не перерисовывает изменения. Если этот флажок установлен, то не происходит никакой перерисовки любого вида. Это применяется к рабочей области, нерабочей области (включая строку заголовка и линейки прокрутки) и любую часть родительского окна, раскрытого в результате перемещения окна. Когда этот флажок установлен, прикладная программа должна явно признать недействительной или перерисовать любые части окна и родительского окна, которые требуют перерисовки.
SWP_NOREPOSITION
То же самое, что и флажок SWP_NOOWNERZORDER .
SWP_NOSENDCHANGING
Предохраняет окно от приема сообщения WM_WINDOWPOSCHANGING .
SWP_NOSIZE
Сохраняет текущий размер (игнорирует cx и cy параметры).
SWP_NOZORDER
Сохраняет текущую Z-последовательность (игнорирует параметр hWndInsertAfter ).
SWP_SHOWWINDOW
Отображает окно на экране.
Если функция завершилась успешно, возвращается значение — не нуль.
Если функция потерпела неудачу, возвращаемое значение — ноль. Чтобы получить расширенную информацию об ошибке, вызовите GetLastError .
Если флажки SWP_SHOWWINDOW или SWP_HIDEWINDOW установлены, окно не может быть перемещено или изменен его размер.
Если Вы изменили некоторые данные окна, используя функцию SetWindowLong , Вы должны вызвать функцию SetWindowPos , чтобы получить ожидаемый результат отменены. Используйте нижеследующую комбинацию флажков для uFlags : SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED .
Окно может быть сделано самым верхним окном или, путем установки параметра hWndInsertAfter в HWND_TOPMOST с гарантией того, что флажок SWP_NOZORDER не установлен, или, путем установки позиции окна в Z-последовательности так, чтобы оно было выше любого существующего самого верхнего окна. Когда не самое верхнее окно делается самым верхним, находящиеся в его собственности окна также делаются самыми верхними. Его владельцы, однако, не изменяются.
Если, ни флажок SWP_NOACTIVATE , ни флажок SWP_NOZORDER не установлен (то есть, когда прикладная программа потребовала, чтобы окно было одновременно, и активизировано, и чтобы его позиция изменилась в Z-последовательности), значение, заданное в hWndInsertAfter , используются только в следующих обстоятельствах:
- Ни флажок HWND_TOPMOST , ни флажок HWND_NOTOPMOST не установлен в параметре hWndInsertAfter .
- Окно, идентифицированное hWnd — не активное окно.
Прикладная программа не может активизировать неактивное окно без такого же переноса его в верхнюю часть Z-последовательности. Прикладные программы могут изменять позицию активного окна в Z-последовательности без ограничений, или они могут активизировать окно, а затем переместить его в верхнюю часть самых верхних или не самых верхних окон.
Если самое верхнее окно переустановлено в нижней части ( HWND_BOTTOM ) Z-последовательности или после любого не самого верхнего окна, оно больше не самое верхнее. Когда самое верхнее окно сделано не самым верхним, его владельцы и находящиеся в его собственности окна также делаются не самыми верхними окнами.
Не самое верхнее окно может владеть самым верхним окном, но наоборот этого произойти не может. Любое окно (например, диалоговое окно) принадлежащее самому верхнему окну самостоятельно делается самым верхним окном, гарантируя, что все окна находящиеся во владении находятся выше их владельца.
Если прикладная программа не в приоритетном режиме, а должна быть в нем, она должна вызвать функцию SetForegroundWindow .