- How to: Create MDI child forms
- Create MDI child forms
- Как создавать дочерние формы MDI How to: Create MDI child forms
- Создание дочерних форм MDI Create MDI child forms
- open every Window form as child to MdiParent
- 6 Answers 6
- Not the answer you’re looking for? Browse other questions tagged c# .net or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
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: 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 .
open every Window form as child to MdiParent
I’m having MdiParent form which has Menu and Submenu Parent Form is Say Form A if I open Form B using submenu option using following code
It opens Form B as child of Form A. Now I want to open Form C from Form B after click the Button on Form B and Form B will be closed and Form C will be opened as Child of Form A Again after click button on Form C , Form C Will be closed and Form B will be opened as Form A
So what can I do to do same ?
6 Answers 6
On FormB button click event write this code:
And in FormC load event write this code:
before B is closed:
In Form B button click where you are calling Form C, you have to assign the MdiParent of FormB to MdiParent of FormC which is FormA. After that you can close FormB.
//FormB Button Click
It’s Work..Try This Code
It’s Work..Try This Code
Not the answer you’re looking for? Browse other questions tagged c# .net or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.