更改表单上的所有按钮

我已经非常接近找到这个解决方案; 在这一点上只缺少一个小细节。

我想做什么:
我想通过代码更改我的窗体(Form1)上的每个按钮的光标样式。 我知道如何使用foreach搜索表单上的所有控件,但我不知道如何通过我编写的例程将此控件作为参数传递。 我将在下面展示我正在做的事情的一个例子。

private void Form1_Load(object sender, EventArgs e) { foreach (Button b in this.Controls) { ChangeCursor(b); // Here is where I'm trying to pass the button as a parameter. Clearly this is not acceptable. } } private void ChangeCursor(System.Windows.Forms.Button Btn) { Btn.Cursor = Cursors.Hand; } 

可能有人给我一个提示吗?

非常感谢你

埃文

我唯一看到的是,如果你有嵌套控件,this.Controls将不会选择那些。 你可以试试这个

 public IEnumerable GetSelfAndChildrenRecursive(Control parent) { List controls = new List(); foreach(Control child in parent.Controls) { controls.AddRange(GetSelfAndChildrenRecursive(child)); } controls.Add(parent); return controls; } 

并打电话

 GetSelfAndChildrenRecursive(this).OfType 

更改

 foreach (Button b in this.Controls) { ChangeCursor(b); // Here is where I'm trying to pass the button as a parameter. // Clearly this is not acceptable. } 

 foreach (Control c in this.Controls) { if (c is Button) { ChangeCursor((Button)c); } } 

并非表单上的每个控件都是按钮。

编辑:您还应该查找嵌套控件。 见Bala R.回答。

与Bala R的答案相同的原则,但我这样做的方式是……

 using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace AppName { public static class ControlExtensions { public static IEnumerable GetAllCtls(this Control control, Type type) { var controls = control.Controls.Cast(); return controls.SelectMany(ctrl => GetAllCtls(ctrl, type)) .Concat(controls) .Where(c => c.GetType() == type); } } } 

然后像这样使用它……

 foreach (Control ctl in this.GetAllCtls(typeof(Button))) { MessageBox.Show("Found a button on the form called '" + ctl.Text + "'"); } 

这对我来说是正确的; 我有没有看到一个问题?

编辑:啊,是的 – 如果你在集合中有非按钮控件,演员表将失败。

您只想传递作为按钮的控件,因此您需要添加IF语句。

如果你的任何控件都无法从按钮inheritance,我认为你的foreach将抛出exception。

尝试这样的事情:

 foreach (Control b in this.Controls) { if (b is Button) ChangeCursor((Button)b); } 

您还可以使用更清晰的语法:

 foreach (Control c in this.Controls) { if (c is Button) { ChangeCursor(c as Button); } }