Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

c# - Change all buttons on a form

I have come very close to finding a solution to this one; just missing one minor detail at this point.

What I am trying to do:
I want to change the cursor style of every button on my Form (Form1) through code. I know how to search through all controls on my form using foreach, but I'm not sure how to pass this control as a parameter through the routine that I wrote. I will show an example of what I am doing below.

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;
}

Might anyone have a tip for me?

Thank you very much

Evan

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only thing I see is that if you have nested controls, this.Controls will not pick those up. you can try this

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;
}

and call

GetSelfAndChildrenRecursive(this).OfType<Button>.ToList()
                  .ForEach( b => b.Cursor = Cursors.Hand);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...