- How to: Create MDI child forms
- Create MDI child forms
- Практическое руководство. Определение активной дочерней MDI-формы How to: Determine the Active MDI Child
- Определение активной дочерней MDI-формы (для копирования ее текста в буфер обмена) To determine the active MDI child (to copy its text to the Clipboard)
- Как создавать дочерние формы MDI How to: Create MDI child forms
- Создание дочерних форм MDI Create MDI child forms
How to: Create MDI child forms
MDI child forms are an essential element of Multiple-Document Interface (MDI) applications, as these forms are the center of user interaction.
In the following procedure, you’ll use Visual Studio to create an MDI child form that displays a RichTextBox control, similar to most word-processing applications. By substituting the System.Windows.Forms control with other controls, such as the DataGridView control, or a mixture of controls, you can create MDI child windows (and, by extension, MDI applications) with diverse possibilities.
Create MDI child forms
Create a new Windows Forms application project in Visual Studio. In the Properties window for the form, set its IsMdiContainer property to true and its WindowsState property to Maximized .
This designates the form as an MDI container for child windows.
From the Toolbox , drag a MenuStrip control to the form. Set its Text property to File.
Click the ellipsis (…) next to the Items property, and click Add to add two child tool strip menu items. Set the Text property for these items to New and Window.
In Solution Explorer, right-click the project, and then select Add > New Item.
In the Add New Item dialog box, select Windows Form (in Visual Basic or in Visual C#) or Windows Forms Application (.NET) (in Visual C++) from the Templates pane. In the Name box, name the form Form2. Select Open to add the form to the project.
The MDI child form you created in this step is a standard Windows Form. As such, it has an Opacity property, which enables you to control the transparency of the form. However, the Opacity property was designed for top-level windows. Do not use it with MDI child forms, as painting problems can occur.
This form will be the template for your MDI child forms.
The Windows Forms Designer opens, displaying Form2.
From the Toolbox, drag a RichTextBox control to the form.
In the Properties window, set the Anchor property to Top, Left and the Dock property to Fill.
This causes the RichTextBox control to completely fill the area of the MDI child form, even when the form is resized.
Double click the New menu item to create a Click event handler for it.
Insert code similar to the following to create a new MDI child form when the user clicks the New menu item.
In the following example, the event handler handles the Click event for MenuItem2 . Be aware that, depending on the specifics of your application architecture, your New menu item may not be MenuItem2 .
In C++, add the following #include directive at the top of Form1.h:
In the drop-down list at the top of the Properties window, select the menu strip that corresponds to the File menu strip and set the MdiWindowListItem property to the Window ToolStripMenuItem.
This enables the Window menu to maintain a list of open MDI child windows with a check mark next to the active child window.
Press F5 to run the application. By selecting New from the File menu, you can create new MDI child forms, which are kept track of in the Window menu item.
When an MDI child form has a MainMenu component (with, usually, a menu structure of menu items) and it is opened within an MDI parent form that has a MainMenu component (with, usually, a menu structure of menu items), the menu items will merge automatically if you have set the MergeType property (and optionally, the MergeOrder property). Set the MergeType property of both MainMenu components and all of the menu items of the child form to MergeItems. Additionally, set the MergeOrder property so that the menu items from both menus appear in the desired order. Moreover, keep in mind that when you close an MDI parent form, each of the MDI child forms raises a Closing event before the Closing event for the MDI parent is raised. Canceling an MDI child’s Closing event will not prevent the MDI parent’s Closing event from being raised; however, the CancelEventArgs argument for the MDI parent’s Closing event will now be set to true . You can force the MDI parent and all MDI child forms to close by setting the CancelEventArgs argument to false .
Практическое руководство. Определение активной дочерней MDI-формы How to: Determine the Active MDI Child
Иногда требуется указать команду, которая будет работать с элементом управления, который имеет фокус на текущей активной дочерней форме. On occasion, you will want to provide a command that operates on the control that has focus on the currently active child form. Например, предположим, что нужно скопировать выбранный текст из текстового поля дочерней формы в буфер обмена. For example, suppose you want to copy selected text from the child form’s text box to the Clipboard. Вы создадите процедуру, которая копирует выбранный текст в буфер обмена с помощью Click события пункта меню Копировать в стандартном меню «Правка». You would create a procedure that copies selected text to the Clipboard using the Click event of the Copy menu item on the standard Edit menu.
Поскольку приложение MDI может иметь много экземпляров одной и той же дочерней формы, процедура должна иметь представление о том, какую форму использовать. Because an MDI application can have many instances of the same child form, the procedure needs to know which form to use. Чтобы указать правильную форму, используйте ActiveMdiChild свойство, которое возвращает дочернюю форму, имеющую фокус или которая была недавно активна. To specify the correct form, use the ActiveMdiChild property, which returns the child form that has the focus or that was most recently active.
Если в форме имеется несколько элементов управления, необходимо также указать, какой элемент управления является активным. When you have several controls on a form, you also need to specify which control is active. Как и ActiveMdiChild свойство, ActiveControl свойство возвращает элемент управления с фокусом на активную дочернюю форму. Like the ActiveMdiChild property, the ActiveControl property returns the control with the focus on the active child form. Приведенная ниже процедура иллюстрирует процедуру копирования, которую можно вызвать из меню дочерней формы, меню в форме MDI или кнопки на панели инструментов. The procedure below illustrates a copy procedure that can be called from a child form menu, a menu on the MDI form, or a toolbar button.
Определение активной дочерней MDI-формы (для копирования ее текста в буфер обмена) To determine the active MDI child (to copy its text to the Clipboard)
В методе скопируйте текст активного элемента управления активной дочерней формы в буфер обмена. Within a method, copy the text of the active control of the active child form to the Clipboard.
В этом примере предполагается, что имеется родительская форма MDI ( Form1 ) с одним или несколькими дочерними ОКНАМИ MDI, содержащими RichTextBox элемент управления. This example assumes there is an MDI parent form ( Form1 ) that has one or more MDI child windows containing a RichTextBox control. Дополнительные сведения см. в разделе Создание родительских MDI-форм. For more information, see Creating MDI Parent Forms.
Как создавать дочерние формы MDI How to: Create MDI child forms
Дочерние MDI-формы являются ключевым элементом приложений с интерфейсом MDI, так как эти формы являются центром взаимодействия с пользователем. MDI child forms are an essential element of Multiple-Document Interface (MDI) applications, as these forms are the center of user interaction.
В следующей процедуре Visual Studio используется для создания дочерней MDI-формы, отображающей RichTextBox элемент управления, аналогично большинству приложений для обработки текстов. In the following procedure, you’ll use Visual Studio to create an MDI child form that displays a RichTextBox control, similar to most word-processing applications. Подставив System.Windows.Forms элемент управления другими элементами управления, такими как DataGridView элемент управления или сочетанием элементов управления, можно создавать дочерние MDI-окна (и, по расширениям, приложения MDI) с различными возможностями. By substituting the System.Windows.Forms control with other controls, such as the DataGridView control, or a mixture of controls, you can create MDI child windows (and, by extension, MDI applications) with diverse possibilities.
Создание дочерних форм MDI Create MDI child forms
Создание нового проекта Windows Forms приложения в Visual Studio. Create a new Windows Forms application project in Visual Studio. В окне свойств формы установите для свойства значение, а для свойства — значение IsMdiContainer true WindowsState Maximized . In the Properties window for the form, set its IsMdiContainer property to true and its WindowsState property to Maximized .
При этом форма назначается в качестве MDI-контейнера для дочерних окон. This designates the form as an MDI container for child windows.
Из Toolbox перетащите элемент управления MenuStrip в форму. From the Toolbox , drag a MenuStrip control to the form. Присвойте Text свойству значение File. Set its Text property to File.
Нажмите кнопку с многоточием (. ) рядом со свойством Items и нажмите кнопку Добавить , чтобы добавить два дочерних пункта меню. Click the ellipsis (…) next to the Items property, and click Add to add two child tool strip menu items. Установите для Text этих элементов свойство » новое » и » окно«. Set the Text property for these items to New and Window.
В обозревателе решений щелкните проект правой кнопкой мыши и выберите пункты Добавить > Новый элемент. In Solution Explorer, right-click the project, and then select Add > New Item.
В диалоговом окне Добавление нового элемента выберите Windows Form (в Visual Basic или в Visual C#) или Windows Forms приложение (.NET) (в Visual C++) в области шаблоны . In the Add New Item dialog box, select Windows Form (in Visual Basic or in Visual C#) or Windows Forms Application (.NET) (in Visual C++) from the Templates pane. В поле имя введите имя формы Form2. In the Name box, name the form Form2. Нажмите кнопку Открыть , чтобы добавить форму в проект. Select Open to add the form to the project.
Дочерняя форма MDI, созданная на этом этапе, является стандартной формой Windows Forms. The MDI child form you created in this step is a standard Windows Form. Таким образом, у нее есть свойство Opacity, которое позволяет управлять прозрачностью формы. As such, it has an Opacity property, which enables you to control the transparency of the form. Однако свойство Opacity предназначено для окон верхнего уровня. However, the Opacity property was designed for top-level windows. Его не следует использовать в дочерних формах MDI, иначе могут возникнуть проблемы с рисованием. Do not use it with MDI child forms, as painting problems can occur.
Эта форма будет шаблоном для дочерних форм MDI. This form will be the template for your MDI child forms.
Откроется конструктор Windows Forms , отображающий Form2. The Windows Forms Designer opens, displaying Form2.
Перетащите элемент управления RichTextBox из панели элементов в форму. From the Toolbox, drag a RichTextBox control to the form.
В окне Свойства задайте Anchor для свойства значение сверху, слева и Dock свойство для заполнения. In the Properties window, set the Anchor property to Top, Left and the Dock property to Fill.
В результате элемент управления RichTextBox будет целиком заполнять область дочерней формы MDI, даже если ее размеры изменятся. This causes the RichTextBox control to completely fill the area of the MDI child form, even when the form is resized.
Дважды щелкните Новый элемент меню, чтобы создать Click для него обработчик событий. Double click the New menu item to create a Click event handler for it.
Вставьте код, аналогичный приведенному ниже, чтобы создать новую дочернюю форму MDI, когда пользователь щелкнет Новый элемент меню. Insert code similar to the following to create a new MDI child form when the user clicks the New menu item.
В примере ниже обработчик событий обрабатывает событие Click для MenuItem2 . In the following example, the event handler handles the Click event for MenuItem2 . Имейте в виду, что в зависимости от особенностей архитектуры приложения Новый пункт меню может не быть MenuItem2 . Be aware that, depending on the specifics of your application architecture, your New menu item may not be MenuItem2 .
В C++ добавьте следующую #include директиву в верхней части Form1. h: In C++, add the following #include directive at the top of Form1.h:
В раскрывающемся списке в верхней части окна Свойства выберите полосу меню, соответствующую полосе меню файл , и задайте MdiWindowListItem для свойства значение окно ToolStripMenuItem . In the drop-down list at the top of the Properties window, select the menu strip that corresponds to the File menu strip and set the MdiWindowListItem property to the Window ToolStripMenuItem.
Это позволяет меню » окно » поддерживать список открытых дочерних окон MDI с галочкой рядом с активным дочерним окном. This enables the Window menu to maintain a list of open MDI child windows with a check mark next to the active child window.
Нажмите клавишу F5 для запуска приложения. Press F5 to run the application. Выбрав пункт создать в меню файл , можно создать дочерние MDI-формы, которые будут храниться в пункте меню окно . By selecting New from the File menu, you can create new MDI child forms, which are kept track of in the Window menu item.
Когда в дочерней форме MDI есть компонент MainMenu (обычно обладающий структурой пунктов меню) и он открыт внутри родительской формы MDI, также имеющей компонент MainMenu (обычно обладающий структурой пунктов меню), пункты меню будут объединены автоматически, если задано свойство MergeType (и, возможно, свойство MergeOrder). When an MDI child form has a MainMenu component (with, usually, a menu structure of menu items) and it is opened within an MDI parent form that has a MainMenu component (with, usually, a menu structure of menu items), the menu items will merge automatically if you have set the MergeType property (and optionally, the MergeOrder property). Установите для свойства MergeType обоих компонентов MainMenu и всех пунктов меню дочерней формы значение MergeItems. Set the MergeType property of both MainMenu components and all of the menu items of the child form to MergeItems. Кроме того, установите свойство MergeOrder таким образом, чтобы пункты обоих меню приводились в нужном порядке. Additionally, set the MergeOrder property so that the menu items from both menus appear in the desired order. Необходимо помнить, что при закрытии родительской формы MDI каждая из дочерних форм MDI создает событие Closing до создания события Closing для родительской формы MDI. Moreover, keep in mind that when you close an MDI parent form, each of the MDI child forms raises a Closing event before the Closing event for the MDI parent is raised. Отмена события Closing дочерней формы MDI не отменяет событие Closing родительской формы MDI. Однако для аргумента CancelEventArgs для события Closing родительской формы MDI будет установлено значение true . Canceling an MDI child’s Closing event will not prevent the MDI parent’s Closing event from being raised; however, the CancelEventArgs argument for the MDI parent’s Closing event will now be set to true . Чтобы принудительно закрыть родительскую и все дочерние формы MDI, задайте для аргумента CancelEventArgs значение false . You can force the MDI parent and all MDI child forms to close by setting the CancelEventArgs argument to false .