如何在Windows窗体中获取窗体的所有控件? [英] How do I get all controls of a form in Windows Forms?
问题描述
我有一个名为 A
的<
A
包含许多不同的控件,包括主 GroupBox
。这个 GroupBox
包含很多表格和其他 GroupBox
es。我想找到一个控制,例如标签索引9的形式为 A
,但我不知道哪个 GroupBox
包含此控件。
我该怎么做?
使用递归...
public static IEnumerable< T> (控制子控件){
T childOfT =子作为T;子类T(此控件控件)其中T:class
{
foreach
if(childOfT!= null){
yield return(T)childOfT; (child.HasChildren){
foreach(T后代在后代< T>(孩子)){
产生返回后代;
}
。
}
}
}
}
您可以使用上面的函数:
var checkBox =(from myForm.Descendants中的c< CheckBox>()
where c.TabIndex == 9
select c).FirstOrDefault();
这将在TabIndex为9的窗体中的任何位置获得第一个CheckBox。显然,您可以使用如果你不是 nofollow noreferrer> LINQ 查询语法,上面的代码可以重写为:
var checkBox = myForm。后裔< CheckBox>()
.FirstOrDefault(x => x.TabIndex == 9);
I have a Form
named A
.
A
contains lots of different controls, including a main GroupBox
. This GroupBox
contains lots of tables and others GroupBox
es. I want to find a control which has e.g. tab index 9 in form A
, but I don't know which GroupBox
contains this control.
How can I do this?
With recursion...
public static IEnumerable<T> Descendants<T>( this Control control ) where T : class
{
foreach (Control child in control.Controls) {
T childOfT = child as T;
if (childOfT != null) {
yield return (T)childOfT;
}
if (child.HasChildren) {
foreach (T descendant in Descendants<T>(child)) {
yield return descendant;
}
}
}
}
You can use the above function like:
var checkBox = (from c in myForm.Descendants<CheckBox>()
where c.TabIndex == 9
select c).FirstOrDefault();
That will get the first CheckBox anywhere within the form that has a TabIndex of 9. You can obviously use whatever criteria you want.
If you aren't a fan of LINQ query syntax, the above could be re-written as:
var checkBox = myForm.Descendants<CheckBox>()
.FirstOrDefault(x=>x.TabIndex==9);
这篇关于如何在Windows窗体中获取窗体的所有控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!