更改表单上的所有按钮

4 c# controls button winforms

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


我想做什么:我想通过代码更改我的窗体(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;
}
Run Code Online (Sandbox Code Playgroud)

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

非常感谢你

埃文

Liv*_*foi 7

更改

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.
}     
Run Code Online (Sandbox Code Playgroud)

foreach (Control c in this.Controls)
{
   if (c is Button)
   {
        ChangeCursor((Button)c);  
   }
}  
Run Code Online (Sandbox Code Playgroud)

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

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


Bal*_*a R 7

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

public IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
{
    List<Control> controls = new List<Control>();

    foreach(Control child in parent.Controls)
    {
        controls.AddRange(GetSelfAndChildrenRecursive(child));
    }

    controls.Add(parent);

    return controls;
}
Run Code Online (Sandbox Code Playgroud)

并打电话

GetSelfAndChildrenRecursive(this).OfType<Button>.ToList()
                  .ForEach( b => b.Cursor = Cursors.Hand);
Run Code Online (Sandbox Code Playgroud)