Hello everyone There is a form that is inherited from other forms I signed this form for the Click event, but it doesn't work for child controls, only for the form itself. In my opinion, it is necessary to register some property. Tell me, please
Asked
Active
Viewed 69 times
0
-
1You may need to something like [this](https://stackoverflow.com/questions/247946/handling-a-click-for-all-controls-on-a-form). Remember to exclude buttons if appropriate. – Andrew Apr 23 '20 at 08:14
-
1You can register the Click event wherever you want it to work. Note that usually you will not want it to work ony many controls like botton of all sorts etc. So, for selected controls you can simply paste the event name into theit events pane. – TaW Apr 23 '20 at 09:17
2 Answers
1
In Windows Forms, contained controls don't inherit the registered events of container control, you'll need to register the event for the controls you want.
You can loop in all the controls to register your intended event:
foreach (Control control in this.Controls)
{
control.Click += myForm_Click;
}

M. Elghamry
- 322
- 2
- 8
-
1This will only include 1st level controls, like a GroupBox but nothing inside.. – TaW Apr 23 '20 at 09:17
-
@TaW - Yup!, noticed that after Eugene Astafiev's answer. Also the link from Andrew on the question has a sample that deals with recursion. – M. Elghamry Apr 23 '20 at 09:32
0
You need to subscribe to control events separately, you can do that recursively for every child control using the following code sample:
void SubscribeToControlsEventsRecursive(ControlCollection collection)
{
foreach (Control c in collection)
{
c.MouseClick += (sender, e) => {/* handle the click here */});
SubscribeToControlsEventsRecursive(c.Controls);
}
}

Eugene Astafiev
- 47,483
- 3
- 24
- 45
-
This will include everything, including each Button. Yes, that's what he may want but chances are he didn't think matters through ;-) – TaW Apr 23 '20 at 09:18
-
1That code looks suspiciously similar to the question I linked in my comment above, LOL. – Andrew Apr 23 '20 at 09:23
-
Are there any other recursive way of subscribing to the events? – Eugene Astafiev Apr 23 '20 at 09:35