System windows forms design

System. Windows. Forms. Design Пространство имен

Содержит классы, обеспечивающие поддержку задания параметров и поведения компонентов Windows Forms во время разработки. Contains classes that support design-time configuration and behavior for Windows Forms components. К числу этих классов относятся классы конструкторов, обеспечивающие поддержку компонентов Windows Forms, набор служб времени разработки, классы UITypeEditor , предназначенные для настройки некоторых типов свойств, и классы для импорта элементов управления ActiveX. These classes consist of designer classes that provide support for Windows Forms components, a set of design-time services; UITypeEditor classes for configuring certain types of properties, and classes for importing ActiveX controls.

Классы

Предоставляет пользовательский интерфейс для настройки свойства Anchor. Provides a user interface for configuring an Anchor property.

Импортирует элементы управления ActiveX и создает оболочку, доступную конструктору. Imports ActiveX controls and generates a wrapper that can be accessed by a designer.

Предоставляет набор параметров для AxImporter. Represents a set of options for an AxImporter.

Представляет параметр метода размещенного элемента управления ActiveX. Represents a parameter of a method of a hosted ActiveX control.

Создает оболочку для элементов управления ActiveX для использования в среде во время разработки. Generates a wrapper for ActiveX controls for use in the design-time environment.

Предоставляет редактор для задания свойства BorderSides. Provides an editor for setting the BorderSides property.

Базовый класс конструктора, расширяющий поведение корневого документа проектирования, поддерживающего вложенные компоненты, в режиме конструктора. Base designer class for extending the design mode behavior of a root design document that supports nested components.

Предоставляет пользовательский интерфейс для WindowsFormsComponentEditor. Provides a user interface for a WindowsFormsComponentEditor.

Предоставляет базовую реализацию для ComponentEditorPage. Provides a base implementation for a ComponentEditorPage.

Предоставляет настройки для области компонентов конструктора. Provides behavior for the component tray of a designer.

Расширяет поведение элемента управления Control в режиме разработки. Extends the design mode behavior of a Control.

Предоставляет доступ к получению и заданию значений параметров для конструктора. Provides access to get and set option values for a designer.

Предоставляет пользовательский интерфейс для задания свойства Dock. Provides a user interface for specifying a Dock property.

Базовый класс конструктора для расширения поведения в режиме разработки и обеспечения представления корневого уровня в режиме разработки для элемента управления Control, который поддерживает вложенные элементы управления и должен получать сообщения прокрутки. Base designer class for extending the design mode behavior of, and providing a root-level design mode view for, a Control that supports nested controls and should receive scroll messages.

Предоставляет систематический способ управления обработчиками событий для текущего документа. Provides a systematic way to manage event handlers for the current document.

Предоставляет вкладку PropertyTab, которая может отображать события для выделения и связывания. Provides a PropertyTab that can display events for selection and linking.

Предоставляет пользовательский интерфейс для выбора имени файла. Provides a user interface for selecting a file name.

Предоставляет пользовательский интерфейс для выбора папки из файловой системы. Provides a user interface for choosing a folder from the file system.

Предоставляет диалоговое окно, которое позволяет пользователю выбирать папку. Represents a dialog box that allows the user to choose a folder. Этот класс не наследуется. This class cannot be inherited.

Сериализирует словари строк. Serializes string dictionaries.

Предоставляет редактор, который может выполнить стандартный поиск файлов точечного рисунка (BMP-файлов). Provides an editor that can perform default file searching for bitmap (.bmp) files.

Определяет набор элементов для производных классов, чтобы предоставить параметры для редактора типов пользовательского интерфейса текстового поля с маской. Defines a set of members for derived classes to provide options for the masked text box UI type editor.

Определяет множество полей CommandID, каждое из которых соответствует командной функции, предоставленной средой узла. Defines a set of CommandID fields that each correspond to a command function provided by the host environment.

Расширяет поведение режима разработки Control, поддерживающего вложенные элементы управления. Extends the design mode behavior of a Control that supports nested controls.

Предоставляет базовый класс для вкладок со свойствами. Provides a base class for property tabs.

Базовый класс конструктора для расширения поведения элемента управления Control, который должен получать сообщения прокрутки, в режиме конструктора. Base designer class for extending the design mode behavior of a Control which should receive scroll messages.

Предоставляет редактор для выбора сочетаний клавиш. Provides an editor for picking shortcut keys.

Задает типы, в которых может отображаться элемент ToolStripItem. Specifies which types a ToolStripItem can appear in. Этот класс не наследуется. This class cannot be inherited.

Предоставляет базовый класс для редакторов, использующих модальный диалог для отображения страницы свойств, похожей на страницу свойств элементов управления ActiveX. Provides a base class for editors that use a modal dialog to display a properties page similar to an ActiveX control’s property page.

Предоставляет доступ для получения и задания значений параметров для конструктора Windows Forms. Provides access to get and set option values for a Windows Forms designer.

Структуры

Представляет окно и значение, указывающее, как полосы прокрутки окна должны быть оформлены тематически при отображении в конструкторе Visual Studio. Represents a window and a value that indicates how its scrollbars should be themed when displayed in the Visual Studio designer.

Читайте также:  Shell ��� ���� ������������� linux

Интерфейсы

Предоставляет методы обработки ссылок к библиотекам ActiveX, библиотекам типов COM или сборкам, а также к управляемым сборкам. Provides methods to resolve references to ActiveX libraries, COM type libraries or assemblies, or managed assemblies.

Определяет метод для получения сведений о том, как полосы прокрутки окна должны быть оформлены стилистически при отображении в конструкторе Visual Studio. Defines a method for getting information about how the scrollbars of windows need to be themed when displayed in the Visual Studio designer.

Предоставляет доступ к службе редактирования меню. Provides access to the menu editing service.

Разрешает взаимодействие с пользовательским интерфейсом объекта среды разработки, в котором размещается конструктор. Enables interaction with the user interface of the development environment object that is hosting the designer.

Предоставляет интерфейс для UITypeEditor для отображения Windows Forms или элементов управления в раскрывающейся области элемента управления сетки свойств в режиме разработки. Provides an interface for a UITypeEditor to display Windows Forms or to display a control in a drop-down area from a property grid control in design mode.

Перечисления

Элементы действий конструктора, которые могут быть связаны с компонентом. Designer action items that can be associated with a component.

Определяет идентификатор, используемый для указания корневой папки для обозревателя папок, при выполнении первоначального просмотра. Defines identifiers used to indicate the root folder for a folder browser to initially browse to.

Определяет идентификаторы, используемые для задания поведения обозревателя FolderNameEditor.FolderBrowser. Defines identifiers used to specify behavior of a FolderNameEditor.FolderBrowser.

Определяет идентификаторы, используемые при указании правил выбора для компонента. Defines identifiers that are used to indicate selection rules for a component.

Значение, указывающее, будут ли полосы прокрутки окна и его дочерних элементов оформлены тематически при отображении в конструкторе Visual Studio. A value that indicates whether the scrollbars of a window and its children will be themed when displayed in the Visual Studio designer.

Задает элементы управления, отображаемые в конструкторе. Specifies controls that are visible in the designer.

Tutorial: Get started with Windows Forms Designer

The Windows Forms Designer provides many tools for building Windows Forms applications. This article illustrates how to build an app using the various tools provided by the designer, including the following tasks:

  • Arrange controls using snaplines.
  • Accomplish designer tasks using smart tags.
  • Set margins and padding for controls.
  • Arrange controls using a TableLayoutPanel control.
  • Partition your control’s layout by using a SplitContainer control.
  • Navigate your layout with the Document Outline window.
  • Position controls with the size and location information display.
  • Set property values using the Properties window.

When you’re finished, you’ll have a custom control that’s been assembled using many of the layout features available in the Windows Forms Designer. This control implements the user interface (UI) for a simple calculator. The following image shows the general layout of the calculator control:

Create the custom control project

The first step is to create the DemoCalculator control project.

Open Visual Studio and create a new Windows Forms Control Library project. Name the project DemoCalculatorLib.

To rename the file, in Solution Explorer, right-click UserControl1.vb or UserControl1.cs, select Rename, and change the file name to DemoCalculator.vb or DemoCalculator.cs. Select Yes when you are asked if you want to rename all references to the code element «UserControl1».

The Windows Forms Designer shows the designer surface for the DemoCalculator control. In this view, you can graphically design the appearance of the control by selecting controls and components from Toolbox and placing them on the designer surface. For more information about custom controls, see Varieties of custom controls.

Design the control layout

The DemoCalculator control contains several Windows Forms controls. In this procedure, you’ll arrange the controls using the Windows Forms Designer.

In the Windows Forms Designer, change the DemoCalculator control to a larger size by selecting the sizing handle in the lower-right corner and dragging it down and to the right. In the lower-right corner of Visual Studio, find the size and location information for controls. Set the size of the control to width 500 and height 400 by watching the size information as you resize the control.

In Toolbox, select the Containers node to open it. Select the SplitContainer control and drag it onto the designer surface.

The SplitContainer is placed on the DemoCalculator control’s designer surface.

The SplitContainer control sizes itself to the fit the size of the DemoCalculator control. Look at the Properties window to see the property settings for the SplitContainer control. Find the Dock property. Its value is DockStyle.Fill, which means the SplitContainer control will always size itself to the boundaries of the DemoCalculator control. Resize the DemoCalculator control to verify this behavior.

In the Properties window, change the value of the Dock property to None .

The SplitContainer control shrinks to its default size and no longer follows the size of the DemoCalculator control.

Select the smart tag glyph () on the upper-right corner of the SplitContainer control. Select Dock in Parent Container to set the Dock property to Fill .

The SplitContainer control docks to the DemoCalculator control’s boundaries.

Several controls offer smart tags to facilitate design. For more information, see Walkthrough: Perform common tasks using Smart Tags on Windows Forms controls.

Читайте также:  Не загружается рабочий стол при запуске windows

Select the vertical border between the panels and drag it to the right, so that most of the space is taken by the left panel.

The SplitContainer divides the DemoCalculator control into two panels with a movable border separating them. The panel on the left will hold the calculator buttons and display, and the panel on the right will show a record of the arithmetic operations performed by the user.

In the Properties window, change the value of the BorderStyle property to Fixed3D .

In Toolbox, select the Common Controls node to open it. Select the ListView control and drag it into the right panel of the SplitContainer control.

Select the ListView control’s smart tag glyph. In the smart tag panel, change the View setting to Details .

In the smart tag panel, select Edit Columns.

The ColumnHeader Collection Editor dialog box opens.

In the ColumnHeader Collection Editor dialog box, select Add to add a column to the ListView control. Change the value of the column’s Text property to History. Select OK to create the column.

In the smart tag panel, select Dock in Parent Container, and then select the smart tag glyph to close the smart tag panel.

From the Containers node Toolbox, drag a TableLayoutPanel control into the left panel of the SplitContainer control.

The TableLayoutPanel control appears on the designer surface with its smart tag panel open. The TableLayoutPanel control arranges its child controls in a grid. The TableLayoutPanel control will hold the DemoCalculator control’s display and buttons. For more information, see Walkthrough: Arrange controls using a TableLayoutPanel.

Select Edit Rows and Columns on the smart tag panel.

The Column and Row Styles dialog box opens.

Select the Add button until five columns are displayed. Select all five columns, and then select Percent in the Size Type box. Set the Percent value to 20. This sets each column to the same width.

Under Show, select Rows.

Select Add until five rows are displayed. Select all five rows, and the select Percent in the Size Type box. Set the Percent value to 20. This sets each row to the same height.

Select OK to accept your changes, and then select the smart tag glyph to close the smart tag panel.

In the Properties window, change the value of the Dock property to Fill .

Populate the control

Now that the layout of the control is set up, you can populate the DemoCalculator control with buttons and a display.

In Toolbox, select the TextBox control icon.

A TextBox control is placed in the first cell of the TableLayoutPanel control.

In the Properties window, change the value of the TextBox control’s ColumnSpan property to 5.

The TextBox control moves to a position that is centered in its row.

Change the value of the TextBox control’s Anchor property to Left , Right .

The TextBox control expands horizontally to span all five columns.

Change the value of the TextBox control’s TextAlign property to Right .

In the Properties window, expand the Font property node. Set Size to 14, and set Bold to true for the TextBox control.

Select the TableLayoutPanel control.

In Toolbox, select the Button icon.

A Button control is placed in the next open cell of the TableLayoutPanel control.

In Toolbox, select the Button icon four more times to populate the second row of the TableLayoutPanel control.

Select all five Button controls by selecting them while holding down the Shift key. Press Ctrl+C to copy the Button controls to the clipboard.

Press Ctrl+V three times to paste copies of the Button controls into the remaining rows of the TableLayoutPanel control.

Select all 20 Button controls by selecting them while holding down the Shift key.

In the Properties window, change the value of the Dock property to Fill .

All the Button controls dock to fill their containing cells.

In the Properties window, expand the Margin property node. Set the value of All to 5.

All the Button controls are sized smaller to create a larger margin between them.

Select button10 and button20, and then press Delete to remove them from the layout.

Select button5 and button15, and then change the value of their RowSpan property to 2. These will be the Clear and = buttons for the DemoCalculator control.

Use the Document Outline window

When your control or form is populated with several controls, you may find it easier to navigate your layout with the Document Outline window.

On the menu bar, choose View > Other Windows > Document Outline.

The Document Outline window shows a tree view of the DemoCalculator control and its constituent controls. Container controls like the SplitContainer show their child controls as subnodes in the tree. You can also rename controls in place using the Document Outline window.

In the Document Outline window, right-click button1, and then select Rename. Change its name to sevenButton.

Using the Document Outline window, rename the Button controls from the designer-generated name to the production name according to the following list:

Читайте также:  Ретро эмуляторы для линукс

button1 to sevenButton

button2 to eightButton

button3 to nineButton

button4 to divisionButton

button5 to clearButton

button6 to fourButton

button7 to fiveButton

button8 to sixButton

button9 to multiplicationButton

button11 to oneButton

button12 to twoButton

button13 to threeButton

button14 to subtractionButton

button15 to equalsButton

button16 to zeroButton

button17 to changeSignButton

button18 to decimalButton

button19 to additionButton

Using the Document Outline and Properties windows, change the Text property value for each Button control name according to the following list:

Change the sevenButton control text property to 7

Change the eightButton control text property to 8

Change the nineButton control text property to 9

Change the divisionButton control text property to / (forward slash)

Change the clearButton control text property to Clear

Change the fourButton control text property to 4

Change the fiveButton control text property to 5

Change the sixButton control text property to 6

Change the multiplicationButton control text property to * (asterisk)

Change the oneButton control text property to 1

Change the twoButton control text property to 2

Change the threeButton control text property to 3

Change the subtractionButton control text property to (hyphen)

Change the equalsButton control text property to = (equals sign)

Change the zeroButton control text property to 0

Change the changeSignButton control text property to +/-

Change the decimalButton control text property to . (period)

Change the additionButton control text property to + (plus sign)

On the designer surface, select all the Button controls by selecting them while holding down the Shift key.

In the Properties window, expand the Font property node. Set Size to 14, and set Bold to true for all the Button controls.

This completes the design of the DemoCalculator control. All that remains is to provide the calculator logic.

Implement event handlers

The buttons on the DemoCalculator control have event handlers that can be used to implement much of the calculator logic. The Windows Forms Designer enables you to implement the stubs of all the event handlers for all the buttons with one selection.

On the designer surface, select all the Button controls by selecting them while holding down the Shift key.

Select one of the Button controls.

The Code Editor opens to the event handlers generated by the designer.

Test the control

Because the DemoCalculator control inherits from the UserControl class, you can test its behavior with the UserControl Test Container. For more information, see How to: Test the run-time behavior of a UserControl.

Press F5 to build and run the DemoCalculator control in the UserControl Test Container.

Select the border between the SplitContainer panels and drag it left and right. The TableLayoutPanel and all its child controls resize themselves to fit in the available space.

When you are finished testing the control, select Close.

Use the control on a form

The DemoCalculator control can be used in other composite controls or on a form. The following procedure describes how to use it.

Create the project

The first step is to create the application project. You’ll use this project to build the application that shows your custom control.

Create a new Windows Forms Application project and name it DemoCalculatorTest.

In Solution Explorer, right-click the DemoCalculatorTest project, and then select Add Reference to open the Add Reference dialog box.

Go to the Projects tab, and then select the DemoCalculatorLib project to add the reference to the test project.

In Solution Explorer, right-click DemoCalculatorTest, and then select Set as StartUp Project.

In the Windows Forms Designer, increase the size of the form to about 700 x 500.

Use the control in the form’s layout

To use the DemoCalculator control in an application, you need to place it on a form.

In Toolbox, expand the DemoCalculatorLib Components node.

Drag the DemoCalculator control from Toolbox onto your form. Move the control to the upper-left corner of the form. When the control is close to the form’s borders, snaplines will appear. Snaplines indicate the distance of the form’s Padding property and the control’s Margin property. Position the control at the location indicated by the snaplines.

Drag a Button control from Toolbox and drop it onto the form.

Move the Button control around the DemoCalculator control and observe where the snaplines appear. You can align your controls precisely and easily using this feature. Delete the Button control when you’re finished.

Right-click the DemoCalculator control, and then select Properties.

Change the value of the Dock property to Fill .

Select the form, and then expand the Padding property node. Change the value of All to 20.

The size of the DemoCalculator control is reduced to accommodate the new Padding value of the form.

Resize the form by dragging the various sizing handles to different positions. Observe how the DemoCalculator control is resized to fit.

Next steps

This article has demonstrated how to construct the user interface for a simple calculator. To continue, you can extend its functionality by implementing the calculator logic, then publish the app using ClickOnce. Or, continue on to a different tutorial where you create a picture viewer using Windows Forms.

Оцените статью