I will tell my requirement. I need to have a keydown
event for each control in the Windows Forms form. It's better to do so rather than manually doing it for all controls if what I have to do for all keydown events is the same.
So I could basically do this:
foreach (Control c in this.Controls)
c.KeyDown+= new KeyEventHandler(c_KeyDown);
But here, the foreach doesn't loop inside those controls which reside inside a groupBox or a tabControl. I mean if the form (this) contains a groupBox or some other container control, then I can get a keydown event for that particular container control. And the foreach
doesn't loop through controls that reside inside that container control.
Question 1: How do I get a keydown event for "all" the controls in a form?
If the above puzzle is solved, then my problem is over.
This is what I can otherwise do:
foreach (Control c in this.Controls)
{
c.KeyDown += new KeyEventHandler(c_KeyDown);
if (c is Container control)
FunctionWhichGeneratesKeyDownForAllItsChildControls(c)
}
I know I will have to go through FunctionWhichGeneratesKeyDownForAllItsChildControls(c)
many times over to get keydown for all controls if there are groupboxes inside a groupbox or so. I can do it. My question is,
Question 2: How do I check if c
is a container control?
A simple recursive function should do it.
private void AddEvent(Control parentCtrl)
{
foreach (Control c in parentCtrl.Controls)
{
c.KeyDown += new KeyEventHandler(c_KeyDown);
AddEvent(c);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With