Windows form get window size

Form. Size Свойство

Определение

Возвращает или задает размер формы. Gets or sets the size of the form.

Значение свойства

Объект Size, представляющий размер формы. A Size that represents the size of the form.

Примеры

В следующем примере показано, как создать форму, которая отображается с уровнем непрозрачности 75%. The following example demonstrates how to create a form that is displayed with an opacity level of 75 percent. В примере кода создается новая форма, которая располагается в центре экрана с Opacity заданным свойством для изменения уровня непрозрачности формы. 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. В примере кода также задается Size свойство для увеличения размера формы, чем размер по умолчанию для формы. 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.

Комментарии

Это свойство позволяет одновременно задать высоту и ширину (в пикселях) формы, а не задавать Height Свойства и по Width отдельности. 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. Если вы хотите задать размер и расположение формы, можно использовать DesktopBounds свойство для изменения размера и расположения формы на основе координат рабочего стола или с помощью Bounds свойства Control класса, чтобы задать размер и расположение формы на основе экранных координат. 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. Значение не может превышать 12 пикселей для каждого измерения экрана (по горизонтали + 12 и по вертикали + 12). The value cannot be greater than 12 pixels over each screen dimension (horizontal + 12 and vertical + 12).

На устройствах Pocket PC можно создать окно с изменяемыми размерами, установив FormBorderStyle для параметра значение None и удалив любой MainMenu элемент управления. On Pocket PC devices, you can create a resizable window by setting FormBorderStyle to None and removing any MainMenu control. На смартфонах можно никогда не изменять размер, Form так как всегда будет заполнен весь экран. On SmartPhone devices, you can never resize a Form — it will always fill the entire screen.

Читайте также:  Два сенсорных экрана windows

Настройка размера и масштаба 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.

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).

Читайте также:  Windows search можно ли отключать

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.

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.

Читайте также:  Создать сетевое место astra linux
Оцените статью