- Практическое руководство. Создание родительских MDI-форм How to: Create MDI Parent Forms
- Создание родительской формы MDI во время разработки Create an MDI parent form at design time
- Get access to parent control from user control — C#
- 9 Answers 9
- Description
- Sample
- More Information
- Update after a comment by Farid-ur-Rahman (He was asking the question)
- Sample
- Sample
- Set the Parent of a Form
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged c# winforms or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Get a Windows Forms control by name in C#
- 14 Answers 14
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Getting parent form name of a form
- 4 Answers 4
Практическое руководство. Создание родительских MDI-форм How to: Create MDI Parent Forms
В этом разделе используется элемент управления MainMenu, который был заменен на элемент управления MenuStrip. This topic uses the MainMenu control, which has been replaced by the MenuStrip control. Элемент управления MainMenu сохраняется для обеспечения обратной совместимости и использования в будущем. The MainMenu control is retained for both backward compatibility and future use, if you choose. Сведения о создании родительской MDI-формы с помощью см MenuStrip . в разделе как создать список окон MDI с помощью MenuStrip. For information about creating a MDI parent Form by using a MenuStrip, see How to: Create an MDI Window List with MenuStrip.
Базой для приложения многодокументного интерфейса (MDI) является родительская MDI-форма. The foundation of a Multiple-Document Interface (MDI) application is the MDI parent form. Это форма, содержащая дочерние MDI-окна, которые являются вложенными окнами, когда пользователи взаимодействуют с MDI-приложением. This is the form that contains the MDI child windows, which are the sub-windows wherein the user interacts with the MDI application. Создание родительской MDI-формы представляет собой несложный процесс, как с помощью конструктора Windows Forms, так и на программном уровне. Creating an MDI parent form is easy, both in the Windows Forms Designer and programmatically.
Создание родительской формы MDI во время разработки Create an MDI parent form at design time
Создайте проект приложения Windows в Visual Studio. Create a Windows Application project in Visual Studio.
В окне Свойства присвойте IsMdiContainer свойству значение true. In the Properties window, set the IsMdiContainer property to true.
При этом форма назначается в качестве MDI-контейнера для дочерних окон. This designates the form as an MDI container for child windows.
При необходимости, при настройке свойств в окне Свойства для свойства WindowState также можно задать значение Maximized, так как управлять дочерними MDI-окнами проще, когда родительская форма развернута. While setting properties in the Properties window, you can also set the WindowState property to Maximized, if you like, as it is easiest to manipulate MDI child windows when the parent form is maximized. Кроме того, следует помнить, что граница родительской MDI-формы будет окрашена в системный цвет (заданный на панели управления Windows), а не в черный цвет, заданный с помощью свойства Control.BackColor. Additionally, be aware that the edge of the MDI parent form will pick up the system color (set in the Windows System Control Panel), rather than the back color you set using the Control.BackColor property.
Перетащите элемент управления MenuStrip из панели элементов в форму. From the Toolbox, drag a MenuStrip control to the form. Создайте пункт меню верхнего уровня — для свойства Text задайте значение &File, пункты меню должны называться &New и &Close. Create a top-level menu item with the Text property set to &File with submenu items called &New and &Close. Также создайте пункт меню верхнего уровня &Window. Also create a top-level menu item called &Window.
Первое меню будет создавать и скрывать пункты меню во время выполнения, а второе меню будет отслеживать открытые дочерние MDI-окна. The first menu will create and hide menu items at run time, and the second menu will keep track of the open MDI child windows. На этом этапе вы создали родительское MDI-окно. At this point, you have created an MDI parent window.
Нажмите клавишу F5 для запуска приложения. Press F5 to run the application. Подробнее о создании дочерних MDI-окон, работающих в родительской MDI-форме, см. в разделе Практическое руководство. Создание дочерних MDI-форм. For information about creating MDI child windows that operate within the MDI parent form, see How to: Create MDI Child Forms.
Get access to parent control from user control — C#
How do I get access to the parent controls of user control in C# (winform). I am using the following code but it is not applicable on all types controls such as ListBox.
Actually, I have to add items in Listbox placed on parent ‘Form’ from a user control.
9 Answers 9
Description
You can get the parent control using Control.Parent .
Sample
So if you have a Control placed on a form this.Parent would be your Form.
Within your Control you can do
More Information
Update after a comment by Farid-ur-Rahman (He was asking the question)
My Control and a listbox (listBox1) both are place on a Form (Form1). I have to add item in a listBox1 when user press a button placed in my Control.
You have two possible ways to get this done.
1. Use `Control.Parent
Sample
MyUserControl
2.
- put a property public MyForm ParentForm < get; set; >to your UserControl
- set the property in your Form
- assuming your ListBox is named listBox1 otherwise change the name
Sample
MyForm
MyUserControl
You can use Control.Parent to get the parent of the control or Control.FindForm to get the first parent Form the control is on. There is a difference between the two in terms of finding forms, so one may be more suitable to use than the other.:
The control’s Parent property value might not be the same as the Form returned by FindForm method. For example, if a RadioButton control is contained within a GroupBox control, and the GroupBox is on a Form, the RadioButton control’s Parent is the GroupBox and the GroupBox control’s Parent is the Form.
Set the Parent of a Form
I have a Windows form from which I would like to open a status form that says «Saving. » and then disapears when the saving is complete. I would like to center this small status form in the middle of the calling form. I’ve tried setting the «StartPosition» propery to «CenterParent», but it doest work. I create the status form from the other form like so:
Wouldn’t the calling form be the «Parent»? When I set a watch for saving it says it has no parent.
and it throws an exception «Top-level control cannot be added to a control.»
How do I center this status window in the calling window?
Thanks in advance
3 Answers 3
i would do something like this:
In SavingForm i would start a timer in the load handler that runs for 500 milliseconds and then closes the form when done. Cleaner that way. ShowDialog will also lock your UI to only display the saving form and not allow the user to monkey with anything.
To set the Owner when you show the form.
Edit: The ShowDialog() method also has an overload that let’s you specify the owner if that is the route you decide to go:
If you pass the parent ( this ) to the Owner, like
then you can access Owner’s properties and methods in the child form (in this case SavingForm ), provided that the Owner’s properties Modifier is set to Internal or Public for each property you need to access (you can either edit the modifier directly in the source code, or via form’s designer properties — there is a Modifier property for each control).
You can find a nice explanation of the differences between Owner, Parent and ParentForm here.
Note: Passing it like saving.Show(this); or saving.ShowDialog(this); did not help in my case.
Not the answer you’re looking for? Browse other questions tagged c# winforms or ask your own question.
Linked
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.
Get a Windows Forms control by name in C#
I have a ToolStripMenuItem called myMenu . How can I access this like so:
This is because I am dynamically generating ToolStripMenuItems from an XML file and need to reference MenuItems by their dynamically generated names.
14 Answers 14
Disregard this, I reinvent wheels.
Assuming you have the menuStrip object and the menu is only one level deep, use:
For deeper menu levels add more SelectMany operators in the statement.
if you want to search all menu items in the strip then use
However, make sure each menu has a different name to avoid exception thrown by key duplicates.
To avoid exceptions you could use FirstOrDefault instead of SingleOrDefault / Single , or just return a sequence if you might have Name duplicates.
this.Controls.Find(name, searchAllChildren) doesn’t find ToolStripItem because ToolStripItem is not a Control
Using the same approach of Philip Wallace, we can do like this:
One of the best way is a single row of code like this:
In this example we search all PictureBox by name in a form
Most important is the second paramenter of find .
if you are certain that the control name exists you can directly use it:
Since you’re generating them dynamically, keep a map between a string and the menu item, that will allow fast retrieval.
This is the actual code that is ran:
Assuming you have Windows.Form Form1 as the parent form which owns the menu you’ve created. One of the form’s attributes is named .Menu . If the menu was created programmatically, it should be the same, and it would be recognized as a menu and placed in the Menu attribute of the Form.
In this case, I had a main menu called File . A sub menu, called a MenuItem under File contained the tag Open and was named menu_File_Open . The following worked. Assuming you
Have a look at the ToolStrip.Items collection. It even has a find method available.
You can do the following:
A simple solution would be to iterate through the Controls list in a foreach loop. Something like this:
So now you have your iterator, child , which is of type Control . Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:
You can use find function in your Form class. If you want to cast (Label) ,(TextView) . etc, in this way you can use special features of objects. It will be return Label object.
name: item name of searched item in the form
true: Search all Children boolean value
Linked
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.
Getting parent form name of a form
I have a Form (form3)which could be opened from two other forms. Form1 and Form2.
how can I get which one is the parent of the form3?
4 Answers 4
The term «parent» has a very strict definition in Windows. The Form class derives from Control like all UI classes do, but it is pretty distinct, it is a top-level window. Very unlike the other controls, like Button and TextBox, they are child windows inside a parent window. The parent of a Form is the desktop window, pretty unlikely that you are interested in that one.
So it is pretty meaningless to talk about «the parent of Form3», it is the same parent as Form1 and Form2 and it doesn’t help you at all to distinguish which one might have displayed the Form3 window.
Windows does have a way to associate two top-level windows with each other, it has the notion of an owner window. It is meant to implement a tool window or a dialog, an owned window is always displayed on top of its owner and is minimized along with its owner. Creating an owned window is simple:
This Show() overload takes an argument that indicates its owner, this can be a reference to a Form1 or Form2 object, depending on where this code appears. Inside the Form3 class, you can find the owner back by using the Owner property.
Which is fairly unlikely what you are really talking about, Winforms is frequently a programmer’s first introduction to object-oriented programming and dealing with object references is often confounding. If you need a reference to a logical parent in Form3 then just write the code so you pass that parent. Which you do by giving the Form3 class a constructor:
And creating the window in Form1 or Form2 just takes:
You can further improve this code in an object-oriented way by designing a base class for Form1 and Form2, one that has members in common that a class like Form3 would be interested in. Or better yet, an interface that both Form1 and Form2 implement, that reduces the coupling significantly. Last but not least, use events to allow Form3 to notify its logical parent. Probably what you are really looking for.