代码很简单,就不用解释了,直接贴↑。
public delegate bool SearchHandler(Control ctrFind);
public class WinSearch<T>
{
//ctr:查找起点控件。
public static T Search(Control ctr, SearchHandler handler)
{
if (handler == null)
throw new Exception("Handler must be not null");
if (ctr == null)
throw new Exception("Parent Control must be not null");
if (!(ctr is Control))
throw new Exception("The fist parameter must be innert from Control");
return SearchProxy(ctr, handler);
}
protected static T SearchProxy(Control ctr,SearchHandler handler)
{
if (ctr.Controls.Count < 1)
{
return default(T);
}
else
{
foreach (Control child in ctr.Controls)
{
if (child is T && handler(child))//注意返回范型类型应是如此才会返回。
{
return (T)(object)child;
}
else
{
foreach (Control ch in child.Controls)
{
object obj = SearchProxy(ch, handler);
if (obj !=null)
{
return (T)obj;
}
}
}
}
return default(T);
}
}
}
测试体:
{
Button btn = WinSearch<Button>.Search(this, new SearchHandler(mehtod));
if (btn != null)
{
MessageBox.Show(btn.Text);
}
}
public bool mehtod(Control ctr)
{
if (ctr.Text =="button2")
return true;
return false;
}