Windows forms mdi form

Создаём MDI приложение с помощью Windows Forms

MDI приложения позволяют отображать несколько дочерних окон внутри одного главного окна. Что даёт возможно более рационально использовать пространство на экране и в ряде случаев повышает удобство работы с многооконным приложением.

Существует два основных подхода к реализации многооконных приложений:

  • Простое приложение.
    Каждое дочернее окно отображается отдельно.
  • MultipleDocumentInterface(MDI).
    Дочерние окна отображаются внутри одного «главного» окна.

Не редко оба подхода комбинируются. Например, небольшие вспомогательные диалоги отображаются отдельно, а окна содержащие основной функционал внутри «главного» окна.

Ниже на скриншоте показан пример простого приложения и приложения MDI.

Простое приложение MDI приложение

Создание приложения MDI

Для того чтобы создать MDI приложение необходимо у формы, которую планируется сделать «главной» установить свойство IsMdiContainer = true. Тогда она сможет размещать внутри себя дочерние формы.

При вызове дочерних форм, чтобы они размещались внутри «главной», необходимо задать «главную» форму в свойстве MdiParent.

Ниже приведён пример вызова дочерней формы из главной.

Как создавать дочерние формы 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 .

Читайте также:  Ati mobility radeon hd 5470 драйвер windows 10 64 bit

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

Form. Mdi Parent Свойство

Определение

Возвращает или задает текущую родительскую MDI-форму этой формы. Gets or sets the current multiple-document interface (MDI) parent form of this form.

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

Объект Form, представляющий родительскую MDI-форму. A Form that represents the MDI parent form.

Исключения

Form, назначенная этому свойству, не помечен как контейнер MDI. The Form assigned to this property is not marked as an MDI container.

-или- -or- Form, назначенная этому свойству, является и дочерней формой, и формой контейнера MDI. The Form assigned to this property is both a child and an MDI container form.

-или- -or- Form, назначенная этому свойству, расположен в другом потоке. The Form assigned to this property is located on a different thread.

Примеры

В следующем примере показано, как создать дочерние формы в приложении MDI. The following example demonstrates how to create child forms in an MDI application. В примере кода создается форма с уникальным текстом для распознавания дочерней формы. The example code creates a form with unique text to identify the child form. В примере свойство используется MdiParent для указания того, что форма является дочерней формой. The example uses the MdiParent property to specify that a form is a child form. В этом примере требуется, чтобы код в примере вызывался из формы, IsMdiContainer для которой свойство имеет значение, true а для формы — целочисленная переменная на уровне закрытого класса с именем childCount . This example requires that the code in the example is called from a form that has its IsMdiContainer property set to true and that the form has a private class level integer variable named childCount .

Комментарии

Чтобы создать дочернюю форму MDI, присвойте Form свойству дочерней формы объект, который будет родительской ФОРМОЙ MDI MdiParent . To create an MDI child form, assign the Form that will be the MDI parent form to the MdiParent property of the child form. Это свойство можно использовать из дочерней MDI-формы для получения глобальной информации, необходимой для всех дочерних форм, или для вызова методов, выполняющих действия со всеми дочерними формами. You can use this property from an MDI child form to obtain global information that all child forms need or to invoke methods that perform actions to all child forms.

Если MenuStrip в дочерней форме MDI есть два элемента управления, при присвоении параметру IsMdiContainer true для родительской формы выполняется слияние содержимого только одного из MenuStrip элементов управления. If there are two MenuStrip controls on an MDI child form, setting IsMdiContainer to true for the parent form merges the contents of only one of the MenuStrip controls. Используйте Merge для слияния содержимого дополнительных дочерних MenuStrip элементов управления в родительской форме MDI. Use Merge to merge the contents of additional child MenuStrip controls on the MDI parent form.

Пошаговое руководство. Создание формы MDI путем слияния меню и элементов управления ToolStrip Walkthrough: Creating an MDI Form with Menu Merging and ToolStrip Controls

Пространство имен System.Windows.Forms поддерживает приложения с интерфейсом MDI, а элемент управления MenuStrip поддерживает слияние меню. The System.Windows.Forms namespace supports multiple document interface (MDI) applications, and the MenuStrip control supports menu merging. Формы MDI также могут содержать элементы управления ToolStrip. MDI forms can also ToolStrip controls.

Читайте также:  Ch340 драйвер windows 10 x64

В этом пошаговом руководстве показано, как использовать ToolStripPanel элементы управления с ФОРМОЙ MDI. This walkthrough demonstrates how to use ToolStripPanel controls with an MDI form. Форма также поддерживает слияние меню с вложенными меню. The form also supports menu merging with child menus. В этом пошаговом руководстве показаны следующие задачи: The following tasks are illustrated in this walkthrough:

Создание проекта Windows Forms. Creating a Windows Forms project.

Создание главного меню для формы. Creating the main menu for your form. Фактическое имя меню будет разным. The actual name of the menu will vary.

Добавление ToolStripPanel элемента управления на панель элементов. Adding the ToolStripPanel control to the Toolbox.

Создание дочерней формы. Creating a child form.

Упорядочение ToolStripPanel элементов управления по z-порядку. Arranging ToolStripPanel controls by z-order.

По завершении у вас будет форма MDI, поддерживающая слияние меню и подвижные ToolStrip элементы управления. When you are finished, you will have an MDI form that supports menu merging and movable ToolStrip controls.

Чтобы скопировать код из этого раздела в виде одного списка, см. раздел как создать форму MDI с помощью слияния меню и элементов управления ToolStrip. To copy the code in this topic as a single listing, see How to: Create an MDI Form with Menu Merging and ToolStrip Controls.

Предварительные требования Prerequisites

Для выполнения этого пошагового руководства потребуется Visual Studio. You’ll need Visual Studio to complete this walkthrough.

Создание проекта Create the project

В Visual Studio создайте проект приложения Windows с именем мдиформ (файл > New > Project > Visual C# или Visual Basic > классический рабочий стол > Windows Forms приложение). In Visual Studio, create a Windows Application project called MdiForm (File > New > Project > Visual C# or Visual Basic > Classic Desktop > Windows Forms Application).

В конструктор Windows Forms выберите форму. In the Windows Forms Designer, select the form.

В окно свойств присвойте свойству значение IsMdiContainer true . In the Properties window, set the value of the IsMdiContainer to true .

Создание главного меню Create the main menu

Родительская форма MDI содержит главное меню. The parent MDI form contains the main menu. Главное меню содержит один пункт меню « окно». The main menu has one menu item named Window. С помощью пункта меню « окно » можно создавать дочерние формы. With the Window menu item, you can create child forms. Пункты меню из дочерних форм объединяются в главное меню. Menu items from child forms are merged into the main menu.

Перетащите элемент управления из панели элементов на MenuStrip форму. From the Toolbox, drag a MenuStrip control onto the form.

Добавьте ToolStripMenuItem к MenuStrip элементу управления и присвойте ему имя Window. Add a ToolStripMenuItem to the MenuStrip control and name it Window.

Выберите элемент управления MenuStrip. Select the MenuStrip control.

В окно свойств задайте MdiWindowListItem для свойства значение ToolStripMenuItem1 . In the Properties window, set the value of the MdiWindowListItem property to ToolStripMenuItem1 .

Добавьте подэлемент в пункт меню окно , а затем назовите Новый подэлемент. Add a subitem to the Window menu item, and then name the subitem New.

В окне Свойства выберите События. In the Properties window, click Events.

Дважды щелкните Click событие. Double-click the Click event.

Конструктор Windows Forms создает обработчик событий для Click события. The Windows Forms Designer generates an event handler for the Click event.

Вставьте следующий код в обработчик событий. Insert the following code into the event handler.

Добавление элемента управления ToolStripPanel на панель элементов Add the ToolStripPanel control to the Toolbox

При использовании MenuStrip элементов управления с ФОРМОЙ MDI необходимо иметь ToolStripPanel элемент управления. When you use MenuStrip controls with an MDI form you must have the ToolStripPanel control. Необходимо добавить ToolStripPanel элемент управления на панель элементов , чтобы создать форму MDI в конструктор Windows Forms. You must add the ToolStripPanel control to the Toolbox to build your MDI form in the Windows Forms Designer.

Откройте панель элементов и перейдите на вкладку все Windows Forms , чтобы отобразить доступные элементы управления Windows Forms. Open the Toolbox, and then click the All Windows Forms tab to show the available Windows Forms controls.

Щелкните правой кнопкой мыши, чтобы открыть контекстное меню, и выберите пункт Выбрать элементы. Right-click to open the shortcut menu, and select Choose Items.

В диалоговом окне Выбор элементов панели элементов прокрутите вниз столбец имя , пока не найдете элемент ToolStripPanel. In the Choose Toolbox Items dialog box, scroll down the Name column until you find ToolStripPanel.

Установите флажок рядом с полем, а затем нажмите кнопку ОК. Select the check box by ToolStripPanel, and then click OK.

ToolStripPanelЭлемент управления появится на панели элементов. The ToolStripPanel control appears in the Toolbox.

Создание дочерней формы Create a child form

В этой процедуре будет определен отдельный класс дочерней формы, имеющий собственный MenuStrip элемент управления. In this procedure, you will define a separate child form class that has its own MenuStrip control. Элементы меню для этой формы объединяются с элементами родительской формы. The menu items for this form are merged with those of the parent form.

Добавьте новую форму с именем ChildForm в проект. Add a new form named ChildForm to the project.

Перетащите элемент управления с панели элементов на MenuStrip дочернюю форму. From the Toolbox, drag a MenuStrip control onto the child form.

Щелкните MenuStrip глиф действий конструктора элемента управления ( ), а затем выберите изменить элементы. Click the MenuStrip control’s designer actions glyph (), and then select Edit Items.

В диалоговом окне Редактор коллекции элементов добавьте новый ToolStripMenuItem именованный чилдменуитем в дочернее меню. In the Items Collection Editor dialog box, add a new ToolStripMenuItem named ChildMenuItem to the child menu.

Тестирование формы Test the form

Нажмите клавишу F5 , чтобы скомпилировать и запустить форму. Press F5 to compile and run your form.

Щелкните пункт меню окно , чтобы открыть меню, и выберите пункт создать. Click the Window menu item to open the menu, and then click New.

Новая дочерняя форма создается в клиентской области MDI формы. A new child form is created in the form’s MDI client area. Меню дочерней формы объединяется с главным меню. The child form’s menu is merged with the main menu.

Читайте также:  Перемешиваются ярлыки windows 10

Закройте дочернюю форму. Close the child form.

Меню дочерней формы удаляется из главного меню. The child form’s menu is removed from the main menu.

Нажмите кнопку создать несколько раз. Click New several times.

Дочерние формы автоматически перечисляются под элементом меню « окно» , так как MenuStrip свойство элемента управления MdiWindowListItem назначено. The child forms are automatically listed under the Window menu item because the MenuStrip control’s MdiWindowListItem property is assigned.

Добавление поддержки ToolStrip Add ToolStrip support

В этой процедуре в ToolStrip родительскую MDI-форму будут добавлены четыре элемента управления. In this procedure, you will add four ToolStrip controls to the MDI parent form. Каждый ToolStrip элемент управления добавляется внутри ToolStripPanel элемента управления, который закрепляется на границе формы. Each ToolStrip control is added inside a ToolStripPanel control, which is docked to the edge of the form.

Перетащите элемент управления из панели элементов на ToolStripPanel форму. From the Toolbox, drag a ToolStripPanel control onto the form.

Выбрав ToolStripPanel элемент управления, дважды щелкните его ToolStrip на панели элементов. With the ToolStripPanel control selected, double-click the ToolStrip control in the Toolbox.

ToolStripЭлемент управления создается в ToolStripPanel элементе управления. A ToolStrip control is created in the ToolStripPanel control.

Выберите элемент управления ToolStripPanel. Select the ToolStripPanel control.

В окно свойств измените значение свойства элемента управления Dock на Left . In the Properties window, change the value of the control’s Dock property to Left.

ToolStripPanelЭлемент управления закрепляется в левой части формы под главным меню. The ToolStripPanel control docks to the left side of the form, underneath the main menu. Размер клиентской области MDI изменяется в соответствии с ToolStripPanel элементом управления. The MDI client area resizes to fit the ToolStripPanel control.

Повторите шаги с 1 по 4. Repeat steps 1 through 4.

Закрепите новый ToolStripPanel элемент управления в верхней части формы. Dock the new ToolStripPanel control to the top of the form.

ToolStripPanelЭлемент управления закреплен под главным меню, но справа от первого ToolStripPanel элемента управления. The ToolStripPanel control is docked underneath the main menu, but to the right of the first ToolStripPanel control. Этот шаг иллюстрирует важность z-порядка в правильном позиционировании ToolStripPanel элементов управления. This step illustrates the importance of z-order in correctly positioning ToolStripPanel controls.

Повторите шаги с 1 по 4 для двух дополнительных ToolStripPanel элементов управления. Repeat steps 1 through 4 for two more ToolStripPanel controls.

Закрепите новые ToolStripPanel элементы управления в правой и нижней части формы. Dock the new ToolStripPanel controls to the right and bottom of the form.

Упорядочить элементы управления ToolStripPanel по Z-порядку Arrange ToolStripPanel controls by Z-order

Положение закрепленного ToolStripPanel элемента управления в форме MDI определяется положением элемента управления в z-порядке. The position of a docked ToolStripPanel control on your MDI form is determined by the control’s position in the z-order. Z-порядок элементов управления можно легко упорядочить в окне «Структура документа». You can easily arrange the z-order of your controls in the Document Outline window.

В меню вид выберите другие окна, а затем щелкните Структура документа. In the View menu, click Other Windows, and then click Document Outline.

Размещение ToolStripPanel элементов управления из предыдущей процедуры является нестандартным. The arrangement of your ToolStripPanel controls from the previous procedure is nonstandard. Это обусловлено неправильным z-порядком. This is because the z-order is not correct. Используйте окно «Структура документа», чтобы изменить z-порядок элементов управления. Use the Document Outline window to change the z-order of the controls.

В окне Структура документа выберите ToolStripPanel4. In the Document Outline window, select ToolStripPanel4.

Несколько раз нажмите кнопку со стрелкой вниз, чтобы ToolStripPanel4 в нижней части списка. Click the down-arrow button repeatedly, until ToolStripPanel4 is at the bottom of the list.

Элемент управления ToolStripPanel4 закрепляется в нижней части формы под другими элементами управления. The ToolStripPanel4 control is docked to the bottom of the form, underneath the other controls.

Выберите ToolStripPanel2. Select ToolStripPanel2.

Нажмите кнопку со стрелкой вниз один раз, чтобы разместить третий элемент управления в списке. Click the down-arrow button one time to position the control third in the list.

Элемент управления ToolStripPanel2 закрепляется в верхней части формы, под главным меню и над другими элементами управления. The ToolStripPanel2 control is docked to the top of the form, underneath the main menu and above the other controls.

Выберите различные элементы управления в окне » Структура документа » и переместите их в различные позиции в z-порядке. Select various controls in the Document Outline window and move them to different positions in the z-order. Обратите внимание на результат z-порядка размещения закрепленных элементов управления. Note the effect of the z-order on the placement of docked controls. Для отмены изменений используйте сочетание клавиш CTRL-Z или отменить в меню Правка . Use CTRL-Z or Undo on the Edit menu to undo your changes.

Контрольная точка — тестирование формы Checkpoint — test your form

Нажмите клавишу F5 , чтобы скомпилировать и запустить форму. Press F5 to compile and run your form.

Щелкните захват ToolStrip элемента управления и перетащите элемент управления в другое положение в форме. Click the grip of a ToolStrip control and drag the control to different positions on the form.

Элемент управления можно перетащить ToolStrip из одного ToolStripPanel элемента управления в другой. You can drag a ToolStrip control from one ToolStripPanel control to another.

Дальнейшие действия Next steps

В этом пошаговом руководстве вы создали родительскую MDI-форму с ToolStrip элементами управления и слиянием меню. In this walkthrough, you have created an MDI parent form with ToolStrip controls and menu merging. ToolStripСемейство элементов управления можно использовать для многих других целей: You can use the ToolStrip family of controls for many other purposes:

Создайте контекстные меню для элементов управления с помощью ContextMenuStrip . Create shortcut menus for your controls with ContextMenuStrip. Дополнительные сведения см. в разделе Общие сведения о компоненте ContextMenu. For more information, see ContextMenu Component Overview.

Создана форма с автоматически заполненным стандартным меню. Created a form with an automatically populated standard menu. Дополнительные сведения см. в разделе Пошаговое руководство. предоставление стандартных пунктов меню в форме. For more information, see Walkthrough: Providing Standard Menu Items to a Form.

Придайте ToolStrip элементам управления профессиональный внешний вид. Give your ToolStrip controls a professional appearance. Дополнительные сведения см. в разделе как задать модуль подготовки отчетов ToolStrip для приложения. For more information, see How to: Set the ToolStrip Renderer for an Application.

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