- Настройка размера и масштаба Windows Forms Adjusting the size and scale of Windows Forms
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related sections
- How to position and size a form (Windows Forms .NET)
- Resize with the designer
- Resize in code
- Resize the current form
- Resize a different form
- Position with the designer
- Position with code
- Move the current form
- Position a different form
- How to: Resize Windows Forms
- Resize a form programmatically
- Change form width and height programmatically
- Change form size by increments programmatically
- Form. Size Property
- Definition
- Property Value
- Examples
- Remarks
- Практическое руководство. Изменение размера формы в Windows Forms How to: Resize Windows Forms
- Программное изменение размера формы Resize a form programmatically
- Программное изменение ширины и высоты формы Change form width and height programmatically
- Изменение размера формы с помощью приращений программными средствами Change form size by increments programmatically
Настройка размера и масштаба 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.
Связанные разделы Related sections
Изменение внешнего вида Windows Forms Changing the appearance of Windows Forms
Ссылки на разделы, в которых описываются другие способы изменения внешнего вида форм Windows Forms. Provides links to topics describing other ways to change the appearance of Windows Forms.
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.
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.
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.
Form. Size Property
Definition
Gets or sets the size of the form.
Property Value
A Size that represents the size of the form.
Examples
The following example demonstrates how to create a form that is displayed with an opacity level of 75 percent. The example code creates a new form that is positioned in the center of the screen with an Opacity property set to change the opacity level of the form. The example code also sets the Size property to provide a larger sized form than the default size of the form. This example requires that the method defined in this example is called from another form in an event handler or other method.
Remarks
This property allows you to set both the height and width (in pixels) of the form at the same time instead of setting the Height and Width properties individually. If you want to set the size and location of a form, you can use the DesktopBounds property to size and locate the form based on desktop coordinates or use the Bounds property of the Control class to set the size and location of the form based on screen coordinates.
The maximum value of this property is limited by the resolution of the screen on which the form runs. The value cannot be greater than 12 pixels over each screen dimension (horizontal + 12 and vertical + 12).
On Pocket PC devices, you can create a resizable window by setting FormBorderStyle to None and removing any MainMenu control. On SmartPhone devices, you can never resize a Form — it will always fill the entire screen.
Практическое руководство. Изменение размера формы в Windows Forms How to: Resize Windows Forms
Размер формы Windows Forms можно указать несколькими способами. You can specify the size of your Windows Form in several ways. Вы можете изменить высоту и ширину формы программными средствами, задав новое значение для свойства Size или изменив свойства Height или Width по отдельности. 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. Если вы используете Visual Studio, можно изменить размер с помощью конструктор Windows Forms. If you’re using Visual Studio, you can change the size using the Windows Forms Designer. См. также руководство. изменение размера Windows Forms с помощью конструктора. Also see How to: Resize Windows Forms Using the Designer.
Программное изменение размера формы Resize a form programmatically
Чтобы определить размер формы во время выполнения, задайте свойство Size формы. Define the size of a form at run time by setting the Size property of the form.
В примере кода ниже размер формы устанавливается равным 100 × 100 пикселей. The following code example shows the form size set to 100 × 100 pixels.
Программное изменение ширины и высоты формы Change form width and height programmatically
Определив свойство Size, измените высоту или ширину формы с помощью свойств Width или Height. After the Size is defined, change either the form height or width by using the Width or Height properties.
В примере кода ниже для ширины формы устанавливается значение 300 пикселей, отсчитываемое от левого края формы. Высота остается неизменной. 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.
Измените Width или Height, задав свойство Size. Change Width or Height by setting the Size property.
Однако в примере ниже показано, что этот подход является более громоздким, чем просто задание свойств Width или Height. 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
Для увеличения размера формы задайте свойства Width или Height. To increment the size of the form, set the Width and Height properties.
В примере ниже ширина формы увеличивается на 200 пикселей по сравнению с первоначальным значением. The following code example shows the width of the form set to 200 pixels wider than the current setting.
Всегда используйте свойство Height или Width для изменения размеров формы, если вы не устанавливаете значения высоты и ширины одновременно, присваивая свойству Size новую структуру Size. 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. Свойство Size возвращает структуру Size, которая является типом значения. 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.