Windows forms resize window

How to: Resize Windows Forms

You can specify the size of your Windows Form in several ways. You can change both the height and the width of the form programmatically by setting a new value for the Size property, or adjust the Height or Width properties individually. If you’re using Visual Studio, you can change the size using the Windows Forms Designer. Also see How to: Resize Windows Forms Using the Designer.

Resize a form programmatically

Define the size of a form at run time by setting the Size property of the form.

The following code example shows the form size set to 100 Г— 100 pixels.

Change form width and height programmatically

After the Size is defined, change either the form height or width by using the Width or Height properties.

The following code example shows the width of the form set to 300 pixels from the left edge of the form, whereas the height stays constant.

Change Width or Height by setting the Size property.

However, as the following code example shows, this approach is more cumbersome than just setting Width or Height properties.

Change form size by increments programmatically

To increment the size of the form, set the Width and Height properties.

The following code example shows the width of the form set to 200 pixels wider than the current setting.

Always use the Height or Width property to change a dimension of a form, unless you are setting both height and width dimensions at the same time by setting the Size property to a new Size structure. The Size property returns a Size structure, which is a value type. You cannot assign a new value to the property of a value type. Therefore, the following code example will not compile.

How to position and size a form (Windows Forms .NET)

When a form is created, the size and location is initially set to a default value. The default size of a form is generally a width and height of 800×500 pixels. The initial location, when the form is displayed, depends on a few different settings.

You can change the size of a form at design time with Visual Studio, and at run time with code.

The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

Resize with the designer

After adding a new form to the project, the size of a form is set in two different ways. First, you can set it is with the size grips in the designer. By dragging either the right edge, bottom edge, or the corner, you can resize the form.

The second way you can resize the form while the designer is open, is through the properties pane. Select the form, then find the Properties pane in Visual Studio. Scroll down to size and expand it. You can set the Width and Height manually.

Resize in code

Even though the designer sets the starting size of a form, you can resize it through code. Using code to resize a form is useful when something about your application determines that the default size of the form is insufficient.

To resize a form, change the Size, which represents the width and height of the form.

Resize the current form

You can change the size of the current form as long as the code is running within the context of the form. For example, if you have Form1 with a button on it, that when clicked invokes the Click event handler to resize the form:

Resize a different form

You can change the size of another form after it’s created by using the variable referencing the form. For example, let’s say you have two forms, Form1 (the startup form in this example) and Form2 . Form1 has a button that when clicked, invokes the Click event. The handler of this event creates a new instance of the Form2 form, sets the size, and then displays it:

If the Size isn’t manually set, the form’s default size is what it was set to during design-time.

Читайте также:  Генератор кода активации для windows

Position with the designer

When a form instance is created and displayed, the initial location of the form is determined by the StartPosition property. The Location property holds the current location the form. Both properties can be set through the designer.

FormStartPosition Enum Description
CenterParent The form is centered within the bounds of its parent form.
CenterScreen The form is centered on the current display.
Manual The position of the form is determined by the Location property.
WindowsDefaultBounds The form is positioned at the Windows default location and is resized to the default size determined by Windows.
WindowsDefaultLocation The form is positioned at the Windows default location and isn’t resized.

The CenterParent value only works with forms that are either a multiple document interface (MDI) child form, or a normal form that is displayed with the ShowDialog method. CenterParent has no affect on a normal form that is displayed with the Show method. To center a form ( form variable) to another form ( parentForm variable), use the following code:

Position with code

Even though the designer can be used to set the starting location of a form, you can use code either change the starting position mode or set the location manually. Using code to position a form is useful if you need to manually position and size a form in relation to the screen or other forms.

Move the current form

You can move the current form as long as the code is running within the context of the form. For example, if you have Form1 with a button on it, that when clicked invokes the Click event handler. The handler in this example changes the location of the form to the top-left of the screen by setting the Location property:

Position a different form

You can change the location of another form after it’s created by using the variable referencing the form. For example, let’s say you have two forms, Form1 (the startup form in this example) and Form2 . Form1 has a button that when clicked, invokes the Click event. The handler of this event creates a new instance of the Form2 form and sets the size:

If the Size isn’t set, the form’s default size is what it was set to at design-time.

Настройка размера и масштаба Windows Forms Adjusting the size and scale of Windows Forms

Этот раздел содержит ссылки на информацию об изменении размера формы Windows Forms. This topic provides links to information about resizing Windows Forms.

в этом разделе In This Section

Практическое руководство. Изменение размера формы в Windows Forms How to: Resize Windows Forms
Инструкции по указанию размера формы Windows Forms. Provides instructions for specifying the size of Windows Forms.

Автоматическое масштабирование в Windows Forms Automatic Scaling in Windows Forms
Описывается, как автоматическое масштабирование обеспечивает корректное отображение формы и ее элементов управления на разных компьютерах. Discusses how automatic scaling enables a form and its controls to be displayed appropriately between machines.

Поддержка высокого DPI в Windows Forms Обсуждается поддержка Windows Forms «для высокого DPI и динамического масштабирования. High DPI Support in Windows Forms Discusses Windows Forms’ support for High DPI and dynamic scaling.

Справочник Reference

Size
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.

TableLayoutPanel
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.

FlowLayoutPanel
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.

Изменение внешнего вида Windows Forms Changing the appearance of Windows Forms
Ссылки на разделы, в которых описываются другие способы изменения внешнего вида форм Windows Forms. Provides links to topics describing other ways to change the appearance of Windows Forms.

Control. Resize Событие

Определение

Происходит при изменении размеров элемента управления. Occurs when the control is resized.

Тип события

Примеры

В следующем примере кода обрабатывается Resize событие объекта Form . The following code example handles the Resize event of a Form. При изменении размера формы обработчик событий гарантирует, что форма остается квадратной (ее Height и Width остается равной). When the form is resized, the event handler ensures that the form stays square (its Height and Width remain equal). Чтобы выполнить этот пример, убедитесь и свяжите этот метод обработки событий с Resize событием формы. To run this example, make sure and associate this event-handling method with the form’s Resize event.

Комментарии

Чтобы определить Size элемент управления с измененным размером, можно привести sender параметр зарегистрированного ControlEventHandler метода к типу Control и получить его Size свойство (или Height свойства по Width отдельности). To determine the Size of the resized control, you can cast the sender parameter of the registered ControlEventHandler method to a Control and get its Size property (or Height and Width properties individually).

Для управления пользовательскими макетами используйте Layout событие вместо события изменения размера. To handle custom layouts, use the Layout event instead of the Resize event. LayoutСобытие вызывается в ответ на Resize событие, а также в ответ на другие изменения, влияющие на макет элемента управления. The Layout event is raised in response to a Resize event, but also in response to other changes that affect the layout of the control.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

Автоматическое масштабирование (Windows Forms .NET) Automatic scaling (Windows Forms .NET)

Автоматическое масштабирование позволяет форме и ее элементам управления, разработанным на одном компьютере с использованием определенного разрешения или шрифтов, правильно отображаться на другом компьютере с другим разрешением или шрифтом. Automatic scaling enables a form and its controls, designed on one machine with a certain display resolution or font, to be displayed appropriately on another machine with a different display resolution or font. Оно гарантирует, что размеры формы и ее элементов управления будут изменяться автоматически в соответствии с приложениями Windows и другими приложениями на компьютерах пользователя и разработчика. It assures that the form and its controls will intelligently resize to be consistent with native windows and other applications on both the users’ and other developers’ machines. Автоматическое масштабирование и стили оформления позволяют приложениям Windows Forms сохранять согласованный внешний вид и поведение на различных компьютерах пользователей, так же как в случае с обычными приложениями Windows. Automatic scaling and visual styles enable Windows Forms applications to maintain a consistent look-and-feel when compared to native Windows applications on each user’s machine.

В большинстве случаев автоматическое масштабирование работает должным образом в Windows Forms. For the most part, automatic scaling works as expected in Windows Forms. Однако внесение изменений в схему шрифтов может быть проблематичным. However, font scheme changes can be problematic.

Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

Потребность в автоматическом масштабировании Need for automatic scaling

Без автоматического масштабирования приложения, разработанные для определенного разрешения экрана или шрифта, будут выглядеть либо слишком маленькими, либо слишком большими при изменении разрешения или шрифта. Without automatic scaling, an application designed for one display resolution or font will either appear too small or too large when that resolution or font is changed. Например, если приложение разработано с использованием базового шрифта Tahoma размером 9 пунктов, то без коррекции оно будет выглядеть слишком маленьким при запуске на компьютере, на котором в качестве системного шрифта используется Tahoma размером 12 пунктов. For example, if the application is designed using Tahoma 9 point as a baseline, without adjustment it will appear too small if run on a machine where the system font is Tahoma 12 point. Текстовые элементы, такие как заголовки, меню, содержимое текстовых полей и т. д., будут меньше, чем в других приложениях. Text elements, such as titles, menus, text box contents, and so on will render smaller than other applications. Более того, размер содержащих текст элементов пользовательского интерфейса, таких как строки заголовков, меню и т. д., зависит от используемого шрифта. Furthermore, the size of user interface (UI) elements that contain text, such as the title bar, menus, and many controls are dependent on the font used. В рассматриваемом примере эти элементы также будут выглядеть относительно меньше. In this example, these elements will also appear relatively smaller.

Аналогичная ситуация возникает, когда приложение разработано для определенного разрешения экрана. An analogous situation occurs when an application is designed for a certain display resolution. Наиболее распространенное разрешение экрана — 96 точек на дюйм (DPI), что соответствует 100 % масштабирования экрана, однако все более распространенными становятся более высокие разрешения, включая 125 %, 150 %, 200 % (что соответствует 120, 144 и 192 DPI) и выше. The most common display resolution is 96 dots per inch (DPI), which equals 100% display scaling, but higher resolution displays supporting 125%, 150%, 200% (which respectively equal 120, 144 and 192 DPI) and above are becoming more common. Без коррекции приложение, особенно графическое, разработанное для одного разрешения, будет отображаться либо слишком большим, либо слишком маленьким при запуске с другим разрешением. Without adjustment, an application, especially a graphics-based one, designed for one resolution will appear either too large or too small when run at another resolution.

Автоматическое масштабирование предназначено для решения таких проблем путем автоматического изменения размеров формы и ее дочерних элементов управления согласно относительному размеру шрифтов и разрешению экрана. Automatic scaling seeks to address these problems by automatically resizing the form and its child controls according to the relative font size or display resolution. Операционная система Windows поддерживает автоматическое масштабирование диалоговых окон с помощью относительной единицы измерения, называемой единицей размера диалогового окна. The Windows operating system supports automatic scaling of dialog boxes using a relative unit of measurement called dialog units. Единица размера диалогового окна основана на системном шрифте, а ее связь с пикселями можно определить с помощью функции GetDialogBaseUnits пакета Win32 SDK. A dialog unit is based on the system font and its relationship to pixels can be determined though the Win32 SDK function GetDialogBaseUnits . При изменении темы, используемой Windows, все диалоговые окна автоматически настраиваются соответствующим образом. When a user changes the theme used by Windows, all dialog boxes are automatically adjusted accordingly. Кроме того, в Windows Forms поддерживается автоматическое масштабирование в соответствии со стандартным системным шрифтом или разрешением экрана. In addition, Windows Forms supports automatic scaling either according to the default system font or the display resolution. При необходимости автоматическое масштабирование можно отключить в приложении. Optionally, automatic scaling can be disabled in an application.

Произвольные сочетания режимов масштабирования на основе разрешения экрана и размера шрифта не поддерживаются. Arbitrary mixtures of DPI and font scaling modes are not supported. Вы без всяких проблем можете масштабировать пользовательский элемент управления в одном режиме (например, на основе разрешения экрана) и поместить его в форму с помощью другого режима (на основе размера шрифта), но использование базовой формы в одном режиме и производной формы в другом может привести к непредвиденным результатам. Although you may scale a user control using one mode (for example, DPI) and place it on a form using another mode (Font) with no issues, but mixing a base form in one mode and a derived form in another can lead to unexpected results.

Автоматическое масштабирование в действии Automatic scaling in action

В Windows Forms для автоматического масштабирования формы и ее содержимого используется описанная ниже логика. Windows Forms uses the following logic to automatically scale forms and their contents:

Во время разработки каждый объект ContainerControl регистрирует режим масштабирования и его текущее разрешение в свойствах AutoScaleMode и AutoScaleDimensions соответственно. At design time, each ContainerControl records the scaling mode and it current resolution in the AutoScaleMode and AutoScaleDimensions, respectively.

Во время выполнения фактическое разрешение хранится в свойстве CurrentAutoScaleDimensions. At run time, the actual resolution is stored in the CurrentAutoScaleDimensions property. Свойство AutoScaleFactor динамически вычисляет отношение между разрешением во время выполнения и разрешением во время разработки. The AutoScaleFactor property dynamically calculates the ratio between the run-time and design-time scaling resolution.

Если при загрузке формы значения CurrentAutoScaleDimensions и AutoScaleDimensions различны, то для масштабирования элемента управления и его дочерних элементов вызывается метод PerformAutoScale. When the form loads, if the values of CurrentAutoScaleDimensions and AutoScaleDimensions are different, then the PerformAutoScale method is called to scale the control and its children. Этот метод приостанавливает размещение и вызывает метод Scale для выполнения фактического масштабирования. This method suspends layout and calls the Scale method to perform the actual scaling. Впоследствии значение AutoScaleDimensions обновляется во избежание прогрессивного масштабирования. Afterwards, the value of AutoScaleDimensions is updated to avoid progressive scaling.

Метод PerformAutoScale также вызывается автоматически в перечисленных ниже ситуациях. PerformAutoScale is also automatically invoked in the following situations:

В ответ на событие OnFontChanged, если используется режим масштабирования Font. In response to the OnFontChanged event if the scaling mode is Font.

Если при возобновлении размещения элементов управления внутри контейнера обнаруживается изменение свойства AutoScaleDimensions или AutoScaleMode. When the layout of the container control resumes and a change is detected in the AutoScaleDimensions or AutoScaleMode properties.

При масштабировании родительского объекта ContainerControl, как указанно выше. As implied above, when a parent ContainerControl is being scaled. Каждый контейнерный элемент управления отвечает за масштабирование своих дочерних элементов с помощью своих собственных коэффициентов масштабирования, а не коэффициентов его родительского контейнера. Each container control is responsible for scaling its children using its own scaling factors and not the one from its parent container.

Поведение дочерних элементов управления при масштабировании может изменяться несколькими способами. Child controls can modify their scaling behavior through several means:

Можно переопределить свойство ScaleChildren, чтобы указать, следует ли масштабировать дочерние элементы управления. The ScaleChildren property can be overridden to determine if their child controls should be scaled or not.

Можно переопределить метод GetScaledBounds для корректировки границ, до которых масштабируется элемент управления, но не логики масштабирования. The GetScaledBounds method can be overridden to adjust the bounds that the control is scaled to, but not the scaling logic.

Можно переопределить метод ScaleControl для изменения логики масштабирования текущего элемента управления. The ScaleControl method can be overridden to change the scaling logic for the current control.

Читайте также:  Код ошибки 0xc0000023 как устранить windows 10
Оцените статью