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:
Mainly pseudo code
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?
Controls.Count>0
, so there is no need to check this explicitly, since ifControls.Count==0
, the foreach loop overControls
does nothing. – Doc BrownKeyPreview
property which allows you to centralize handling of keyboard events. – Ben Voigt