- Form. Auto Size Mode Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Label. Auto Size Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- AutoSize Property Overview
- AutoSize Behavior
- AutoSizeMode Property
- Controls That Support the AutoSize Property
- Form. Auto Size Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- Автоматическое масштабирование (Windows Forms .NET) Automatic scaling (Windows Forms .NET)
- Потребность в автоматическом масштабировании Need for automatic scaling
- Автоматическое масштабирование в действии Automatic scaling in action
Form. Auto Size Mode Свойство
Определение
Возвращает или задает режим, с помощью которого форма может автоматически изменять свои размеры. Gets or sets the mode by which the form automatically resizes itself.
Значение свойства
Перечислимое значение AutoSizeMode. An AutoSizeMode enumerated value. Значение по умолчанию — GrowOnly. The default is GrowOnly.
Исключения
Значение не является допустимым значением AutoSizeMode. The value is not a valid AutoSizeMode value.
Примеры
В следующем примере показана форма, созданная с помощью кода, который автоматически изменяет размер в соответствии с содержимым. The following example shows a form created using code that automatically resizes to fit its contents. При запуске форма отображает Label , а TextBox для ввода URL-адреса, а также Button для отображения этого URL-адреса в браузере пользователя по умолчанию. When run, the form displays a Label, a TextBox for entering a URL, and a Button for displaying that URL inside of the user’s default Web browser. В примере используется FlowLayoutPanel для размещения вложенных элементов управления один за другим. The example uses a FlowLayoutPanel to lay out the contained controls one after the other. Он также задает AutoSize и AutoSizeMode для увеличения и уменьшения в соответствии с содержимым его формы. It also sets the AutoSize and AutoSizeMode to grow and shrink to fit the contents of its form.
Комментарии
Присвоение AutoSizeMode свойству нового значения приводит к повторному размещению формы. Setting the AutoSizeMode property to a new value causes the form to be laid out again.
Форма не изменяет размер автоматически в конструкторе форм Visual Studio независимо от значений AutoSize AutoSizeMode свойств и. A form does not automatically resize in the Visual Studio forms designer, regardless of the values of the AutoSize and AutoSizeMode properties. Форма правильно изменяет размер самого себя во время выполнения в соответствии со значениями этих двух свойств. The form correctly resizes itself at run time according to the values of these two properties. В отличие от этого, пользователь UserControl автоматически изменяет свой размер как во время разработки, так и во время выполнения. By contrast, a custom UserControl automatically resizes itself both at design time and at run time.
Label. Auto Size Свойство
Определение
Получает или задает значение, указывающее, изменяются ли размеры элемента управления автоматически для отображения всего его содержимого. Gets or sets a value indicating whether the control is automatically resized to display its entire contents.
Значение свойства
Значение true , если размеры элемента управления подгоняются под ширину его содержимого; в противном случае — false . true if the control adjusts its width to closely fit its contents; otherwise, false .
При добавлении в форму с использованием конструктора значение по умолчанию — true . When added to a form using the designer, the default value is true . При создании экземпляра из кода значение по умолчанию — false . When instantiated from code, the default value is false .
Примеры
В следующем примере кода показано AutoSize свойство. The following code example demonstrates the AutoSize property. Чтобы выполнить этот пример, вставьте следующий код в форму и вызовите InitializeLabel метод из конструктора или Load метода формы. To run this example, paste the following code in a form and call the InitializeLabel method from the form’s constructor or Load method.
Комментарии
Если для этого свойства задано значение true , то параметр Label изменяет ширину для вывода всего содержимого. When this property is set to true , the Label adjusts its width to display its entire contents. Обычно это свойство имеет значение true при использовании Label элемента управления для вывода различной длины текста, например состояния процесса приложения. This property is typically set to true when you use a Label control to display various lengths of text, such as the status of an application process. Это свойство также можно использовать, когда приложение будет отображать текст на различных языках, а размер текста может увеличиваться или уменьшаться в зависимости от языковых параметров в Windows. You can also use this property when the application will display text in various languages, and the size of the text might increase or decrease based on the language settings in Windows.
Если шрифт превышает высоту объекта Label и имеет значение, то для отображения AutoEllipsis true текста необходимо задать параметр AutoSize false . If the font is taller than the height of the Label and AutoEllipsis is true , you must set AutoSize to false for text to be drawn.
AutoSize Property Overview
The AutoSize property enables a control to change its size, if necessary, to attain the value specified by the PreferredSize property. You adjust the sizing behavior for specific controls by setting the AutoSizeMode property.
AutoSize Behavior
Only some controls support the AutoSize property. In addition, some controls that support the AutoSize property also support the AutoSizeMode property.
The AutoSize property produces somewhat different behavior, depending on the specific control type and the value of the AutoSizeMode property, if the property exists. The following table describes the behaviors that are always true and provides a brief description of each:
Always true behavior | Description |
---|---|
Automatic sizing is a run-time feature. | This means it never grows or shrinks a control and then has no further effect. |
If a control changes size, the value of its Location property always remains constant. | When a control’s contents cause it to grow, the control grows toward the right and downward. Controls do not grow to the left. |
The Dock and Anchor properties are honored when AutoSize is true . | The value of the control’s Location property is adjusted to the correct value. Note The Label control is the exception to this rule. When you set the value of a docked Label control’s AutoSize property to true , the Label control will not stretch. |
A control’s MaximumSize and MinimumSize properties are always honored, regardless of the value of its AutoSize property. | The MaximumSize and MinimumSize properties are not affected by the AutoSize property. |
There is no minimum size set by default. | This means that if a control is set to shrink under AutoSize and it has no contents, the value of its Size property is 0,0. In this case, your control will shrink to a point, and it will not be readily visible. |
If a control does not implement the GetPreferredSize method, the GetPreferredSize method returns last value assigned to the Size property. | This means that setting AutoSize to true will have no effect. |
A control in a TableLayoutPanel cell always shrinks to fit in the cell until its MinimumSize is reached. | This size is enforced as a maximum size. This is not the case when the cell is part of an AutoSize row or column. |
AutoSizeMode Property
The AutoSizeMode property provides more fine-grained control over the default AutoSize behavior. The AutoSizeMode property specifies how a control sizes itself to its content. The content, for example, could be the text for a Button control or the child controls for a container.
The following table shows the AutoSizeMode settings and a description of the behavior each setting elicits.
AutoSizeMode setting | Behavior |
---|---|
GrowAndShrink | The control grows or shrinks to encompass its contents. The MinimumSize and MaximumSize values are honored, but the current value of the Size property is ignored. This is the same behavior as controls with the AutoSize property and no AutoSizeMode property. |
GrowOnly | The control grows as much as necessary to encompass its contents, but it will not shrink smaller than the value specified by its Size property. This is the default value for AutoSizeMode . |
Controls That Support the AutoSize Property
The following table lists the controls that support the AutoSize and AutoSizeMode properties.
Form. Auto Size Свойство
Определение
Изменяет размеры формы в соответствии со значением AutoSizeMode. Resize the form according to the setting of AutoSizeMode.
Значение свойства
Значение true , если размеры формы будут автоматически изменены; false , если их необходимо изменять вручную. true if the form will automatically resize; false if it must be manually resized.
Примеры
В следующем примере показана форма, созданная с помощью кода, который автоматически изменяет размер в соответствии с содержимым. The following example shows a form created using code that automatically resizes to fit its contents. При запуске форма отображает Label , а TextBox для ввода URL-адреса, а также Button для отображения этого URL-адреса в браузере пользователя по умолчанию. When run, the form displays a Label, a TextBox for entering a URL, and a Button for displaying that URL inside of the user’s default Web browser. В примере используется FlowLayoutPanel для размещения вложенных элементов управления один за другим. The example uses a FlowLayoutPanel to lay out the contained controls one after the other. Он также задает AutoSize и AutoSizeMode для увеличения и уменьшения в соответствии с содержимым его формы. It also sets the AutoSize and AutoSizeMode to grow and shrink to fit the contents of its form.
Комментарии
Используйте AutoSize , чтобы принудительно изменить размер формы в соответствии с ее содержимым. Use AutoSize to force a form to resize to fit its contents.
Форма не изменяет размер автоматически в конструкторе форм Visual Studio независимо от значений AutoSize AutoSizeMode свойств и. A form does not automatically resize in the Visual Studio forms designer, regardless of the values of the AutoSize and AutoSizeMode properties. Форма правильно изменяет размер самого себя во время выполнения в соответствии со значениями этих двух свойств. The form correctly resizes itself at run time according to the values of these two properties. В отличие от этого, пользователь UserControl автоматически изменяет свой размер как во время разработки, так и во время выполнения. By contrast, a custom UserControl automatically resizes itself both at design time and at run time.
При использовании AutoSize MinimumSize Свойства и учитываются MaximumSize , но текущее значение Size свойства игнорируется. When using AutoSize, the MinimumSize and MaximumSize properties are respected, but the current value of the Size property is ignored. Использование AutoSize , а AutoSizeMode также визуализация AutoScroll свойства, излишнего, так как невозможно сжать форму, чтобы скрыть ее вложенные элементы управления из представления. Using AutoSize and AutoSizeMode also renders the AutoScroll property superfluous, as there is no way to shrink the form to hide its contained controls from view.
Сведения о AutoSizeMode принципах работы формы AutoSize , когда имеет значение, см. в разделе Перечисление true . See the AutoSizeMode enumeration for information on how a form behaves when AutoSize is true .
Автоматическое масштабирование (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.