- Form. Form Border Style Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Отрисовка элементов управления с применением визуальных стилей Rendering Controls with Visual Styles
- Классы отрисовки для общих элементов управления Rendering Classes for Common Controls
- Элемент стиля оформления и классы отрисовки Visual Style Element and Rendering Classes
- Включение стилей оформления Enabling Visual Styles
- Проверка поддержки стилей оформления Checking for Visual Styles Support
Form. Form Border Style Свойство
Определение
Возвращает или задает стиль границы формы. Gets or sets the border style of the form.
Значение свойства
Объект FormBorderStyle, представляющий стиль отображаемой границы для формы. A FormBorderStyle that represents the style of border to display for the form. Значение по умолчанию — FormBorderStyle.Sizable . The default is FormBorderStyle.Sizable .
Исключения
Заданное значение находится вне диапазона допустимых значений. The value specified is outside the range of valid values.
Примеры
В следующем примере создается новый экземпляр класса Form и вызывается ShowDialog метод для вывода формы в виде диалогового окна. The following example creates a new instance of a Form and calls the ShowDialog method to display the form as a dialog box. В примере задаются FormBorderStyle AcceptButton свойства,, CancelButton ,, MinimizeBox MaximizeBox и, StartPosition чтобы изменить внешний вид и функциональность формы на диалоговое окно. The example sets the FormBorderStyle, AcceptButton, CancelButton, MinimizeBox, MaximizeBox, and StartPosition properties to change the appearance and functionality of the form to a dialog box. В примере также используется Add метод Controls коллекции формы для добавления двух Button элементов управления. The example also uses the Add method of the form’s Controls collection to add two Button controls. В примере свойство используется HelpButton для вывода кнопки справки в строке заголовка диалогового окна. The example uses the HelpButton property to display a help button in the caption bar of the dialog box.
Комментарии
Стиль границы формы определяет, как выглядит внешний край формы. The border style of the form determines how the outer edge of the form appears. В дополнение к изменению границ для формы, определенные стили границ запрещают размер формы. In addition to changing the border display for a form, certain border styles prevent the form from being sized. Например, FormBorderStyle.FixedDialog стиль границы изменяет границу формы на форму диалогового окна и предотвращает изменение размера формы. For example, the FormBorderStyle.FixedDialog border style changes the border of the form to that of a dialog box and prevents the form from being resized. Стиль границы также может влиять на размер или доступность раздела заголовка в форме. The border style can also affect the size or availability of the caption bar section of a form.
С помощью Sizable стиля невозможно изменить размер окна ниже определенного минимального значения, даже если для параметра задано значение ControlBox false и ему присвоена строка нулевой длины Text . With the Sizable style, it is impossible to resize the window below a certain minimum value, even if you have set ControlBox to false and assigned a zero-length string to Text. Рассмотрите возможность обойти это, используя SizableToolWindow вместо этого стиль. Consider working around this by using the SizableToolWindow style instead.
Отрисовка элементов управления с применением визуальных стилей Rendering Controls with Visual Styles
.NET Framework обеспечивает поддержку отрисовки элементов управления и других элементов ПОЛЬЗОВАТЕЛЬСКОГО интерфейса Windows с помощью визуальных стилей в операционных системах, поддерживающих их. The .NET Framework provides support for rendering controls and other Windows user interface (UI) elements using visual styles in operating systems that support them. В этом разделе обсуждаются различные уровни поддержки в .NET Framework для отрисовки элементов управления и других элементов пользовательского интерфейса с использованием текущего визуального стиля операционной системы. This topic discusses the several levels of support in the .NET Framework for rendering controls and other UI elements with the current visual style of the operating system.
Классы отрисовки для общих элементов управления Rendering Classes for Common Controls
Отрисовкой элемента управления называется рисование пользовательского интерфейса для элемента управления. Rendering a control refers to drawing the user interface of a control. Пространство имен System.Windows.Forms предоставляет класс ControlPaint для отрисовки некоторых общих элементов управления Windows Forms. The System.Windows.Forms namespace provides the ControlPaint class for rendering some common Windows Forms controls. Однако этот класс рисует элементы управления в классическом стиле Windows, что может затруднять обеспечение согласованности пользовательского интерфейса при рисовании пользовательских элементов управления в приложениях с включенными стилями оформления. However, this class draws controls in the classic Windows style, which can make it difficult to maintain a consistent UI experience when drawing custom controls in applications with visual styles enabled.
.NET Framework 2,0 содержит классы в System.Windows.Forms пространстве имен, которые отображают части и состояния стандартных элементов управления с визуальными стилями. The .NET Framework 2.0 includes classes in the System.Windows.Forms namespace that render the parts and states of common controls with visual styles. Каждый из этих классов содержит методы static для рисования элемента управления или его частей в определенном состоянии с использованием текущего стиля оформления операционной системы. Each of these classes includes static methods for drawing the control or parts of the control in a particular state with the current visual style of the operating system.
Некоторые из этих классов предназначены для рисования связанного элемента управления независимо от доступности стилей оформления. Some of these classes are designed to draw the related control regardless of whether visual styles are available. Если стили оформления включены, элементы класса будут рисовать связанный элемент управления с применением стилей оформления. Если стили оформления отключены, элементы класса будет рисовать элемент управления в классическом стиле Windows. If visual styles are enabled, then the class members will draw the related control with visual styles; if visual styles are disabled, then the class members will draw the control in the classic Windows style. К таким классам относятся следующие: These classes include:
Другие классы могут нарисовать связанный элемент управления только при доступных стилях оформления, в противном случае их элементы выдают исключение. Other classes can only draw the related control when visual styles are available, and their members will throw an exception if visual styles are disabled. К таким классам относятся следующие: These classes include:
Дополнительные сведения об использовании этих классов для рисования элемента управления см. в разделе How to: Use a Control Rendering Class. For more information on using these classes to draw a control, see How to: Use a Control Rendering Class.
Элемент стиля оформления и классы отрисовки Visual Style Element and Rendering Classes
Пространство имен System.Windows.Forms.VisualStyles содержит классы, которые можно использовать для рисования любого элемента управления или элемента пользовательского интерфейса, поддерживаемого стилями оформления, и получения сведений о нем. The System.Windows.Forms.VisualStyles namespace includes classes that can be used to draw and get information about any control or UI element that is supported by visual styles. К поддерживаемым элементам управления относятся общие элементы управления с классом отрисовки в пространстве имен System.Windows.Forms (см. предыдущий раздел), а также другие элементы управления, такие как элементы управления «Вкладка» и элементы управления «Главная панель». Supported controls include common controls that have a rendering class in the System.Windows.Forms namespace (see the previous section), as well as other controls, such as tab controls and rebar controls. В число других поддерживаемых элементов пользовательского интерфейса входят части меню Пуск , панели инструментов и неклиентской области окон. Other supported UI elements include the parts of the Start menu, the taskbar, and the nonclient area of windows.
Главными классами пространства имен System.Windows.Forms.VisualStyles являются VisualStyleElement и VisualStyleRenderer. The main classes of the System.Windows.Forms.VisualStyles namespace are VisualStyleElement and VisualStyleRenderer. VisualStyleElement — это класс платформы для идентификации любого элемента управления или элемента пользовательского интерфейса, поддерживаемого стилями оформления. VisualStyleElement is a foundation class for identifying any control or user interface element supported by visual styles. В дополнение к самому VisualStyleElement пространство имен System.Windows.Forms.VisualStyles содержит много вложенных классов VisualStyleElement со свойствами static , которые возвращают VisualStyleElement для каждого состояния элемента управления, части элемента управления или другого элемента пользовательского интерфейса, поддерживаемого стилями оформления. In addition to VisualStyleElement itself, the System.Windows.Forms.VisualStyles namespace includes many nested classes of VisualStyleElement with static properties that return a VisualStyleElement for every state of a control, control part, or other UI element supported by visual styles.
VisualStyleRenderer предоставляет методы для рисования каждого VisualStyleElement , определяемого текущим стилем оформления операционной системы, и получения сведений о нем. VisualStyleRenderer provides the methods that draw and get information about each VisualStyleElement defined by the current visual style of the operating system. Сведения, которые можно получить об элементе, включают его размер по умолчанию, тип фона и определения цвета. Information that can be retrieved about an element includes its default size, background type, and color definitions. VisualStyleRenderer использует программу-оболочку для функций API стилей оформления (UxTheme) из части оболочки Windows пакета SDK платформы Windows. VisualStyleRenderer wraps the functionality of the visual styles (UxTheme) API from the Windows Shell portion of the Windows Platform SDK. Дополнительные сведения см. в разделе Включение визуальных стилей. For more information, see Enabling Visual Styles.
Включение стилей оформления Enabling Visual Styles
Чтобы включить стили оформления для приложения, написанного для .NET Framework версии 1,0, программист должен включить манифест приложения, который указывает, что для рисования элементов управления будет использоваться ComCtl32.dll версии 6 или более поздней. To enable visual styles for an application written for the .NET Framework version 1.0, programmers must include an application manifest that specifies that ComCtl32.dll version 6 or later will be used to draw controls. Приложения, созданные с помощью .NET Framework версии 1,1 или более поздней, могут использовать Application.EnableVisualStyles метод Application класса. Applications built with the .NET Framework version 1.1 or later can use the Application.EnableVisualStyles method of the Application class.
Проверка поддержки стилей оформления Checking for Visual Styles Support
Свойство RenderWithVisualStyles класса Application указывает, будет ли текущее приложение рисовать элементы управления с помощью стилей оформления. The RenderWithVisualStyles property of the Application class indicates whether the current application is drawing controls with visual styles. При рисовании пользовательского элемента управления можно проверить значение RenderWithVisualStyles , чтобы определить, следует ли учитывать стили оформления при отрисовке элемента управления. When painting a custom control, you can check the value of RenderWithVisualStyles to determine whether you should render your control with or without visual styles. В следующей таблице перечислены четыре условия, которые должны выполняться, чтобы RenderWithVisualStyles возвратил true . The following table lists the four conditions that must exist for RenderWithVisualStyles to return true .
Условие Condition | Примечания Notes |
---|---|
Операционная система поддерживает стили оформления. The operating system supports visual styles. | Чтобы проверить это условие отдельно, используйте свойство IsSupportedByOS класса VisualStyleInformation . To verify this condition separately, use the IsSupportedByOS property of the VisualStyleInformation class. |
Пользователь включил стили оформления в операционной системе. The user has enabled visual styles in the operating system. | Чтобы проверить это условие отдельно, используйте свойство IsEnabledByUser класса VisualStyleInformation . To verify this condition separately, use the IsEnabledByUser property of the VisualStyleInformation class. |
Стили оформления включены в приложении. Visual styles are enabled in the application. | Стили оформления можно включить в приложении, вызвав метод Application.EnableVisualStyles или воспользовавшись манифестом приложения, указывающим, что для рисования элементов управления будет применяться ComCtl32.dll версии 6 или более поздней. Visual styles can be enabled in an application by calling the Application.EnableVisualStyles method or by using an application manifest that specifies that ComCtl32.dll version 6 or later will be used to draw controls. |
Стили оформления используются для рисования клиентской области окон приложений. Visual styles are being used to draw the client area of application windows. | Чтобы проверить это условие отдельно, используйте свойство VisualStyleState класса Application и убедитесь, что оно имеет значение VisualStyleState.ClientAreaEnabled или VisualStyleState.ClientAndNonClientAreasEnabled. To verify this condition separately, use the VisualStyleState property of the Application class and verify that it has the value VisualStyleState.ClientAreaEnabled or VisualStyleState.ClientAndNonClientAreasEnabled. |
Чтобы определить, когда пользователь включает или отключает стили оформления или переключается между ними, проверьте наличие значения UserPreferenceCategory.VisualStyle в обработчиках для событий SystemEvents.UserPreferenceChanging или SystemEvents.UserPreferenceChanged . To determine when a user enables or disables visual styles, or switches from one visual style to another, check for the UserPreferenceCategory.VisualStyle value in the handlers for the SystemEvents.UserPreferenceChanging or SystemEvents.UserPreferenceChanged events.
Если вы хотите использовать VisualStyleRenderer для отрисовки элемента управления или элемента пользовательского интерфейса, когда пользователь включает стили оформления или переключается между ними, это нужно сделать при обработке события UserPreferenceChanged вместо UserPreferenceChanging . If you want to use VisualStyleRenderer to render a control or UI element when the user enables or switches visual styles, make sure that you do this when handling the UserPreferenceChanged event instead of the UserPreferenceChanging event. Если вы используете класс VisualStyleRenderer при обработке UserPreferenceChanging, возникнет исключение. An exception will be thrown if you use the VisualStyleRenderer class when handling UserPreferenceChanging.