如何在Windows窗体窗体中循环浏览所有控件,或者如何查找特定控件是否为容器控件? [英] How to loop through all controls in a Windows Forms form or how to find if a particular control is a container control?
问题描述
我会说出我的要求.我需要在 Windows窗体中的每个控件都有一个 keydown
事件.形式.如果我对所有按键事件必须执行的操作都相同,那么最好对所有控件执行此操作,而不要手动进行.
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);
但是在这里,foreach不会在位于groupBox或tabControl内的那些控件内循环.我的意思是,如果表单(this)包含一个groupBox或其他容器控件,那么我可以获得该特定容器控件的keydown事件.而且 foreach
不会遍历位于该容器控件内的控件.
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.
问题1:如何获得针对全部"广告素材的keydown事件?控件的形式?
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.
这是我可以做的:
foreach (Control c in this.Controls)
{
c.KeyDown += new KeyEventHandler(c_KeyDown);
if (c is Container control)
FunctionWhichGeneratesKeyDownForAllItsChildControls(c)
}
我知道我必须经历多次 FunctionWhichGeneratesKeyDownForAllItsChildControls(c)
多次,以获取所有控件的键控(如果一个或多个左右的boxbox都在其中).我能做到.我的问题是,
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,
问题2:如何检查 c
是否是容器控件?
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);
}
}
这篇关于如何在Windows窗体窗体中循环浏览所有控件,或者如何查找特定控件是否为容器控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!