Click here to Skip to main content
15,910,872 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
im trying to use my public method to every form. what i want is when the method is call, find all the buttons in a form and play system sound in each button when it is CLICKED.

What I have tried:

public static void setButtons(Form  f)
{
    foreach (Control c in f.Controls)
    {
        Button btn = c as Button;

        if (c == btn)
        {
            System.Media.SystemSounds.Beep.Play();
        }
    }
}
Posted
Updated 3-Dec-17 0:31am

You need to use the control's InvokeRequired property, see:
How to: Make Thread-Safe Calls to Windows Forms Controls | Microsoft Docs[^]
 
Share this answer
 
public static void setButtons(Form  f)
        {
            foreach (Control c in f.Controls)
            {
                Button btn = c as Button;
 
                if (c == btn)
                {
					btn.Click += btn_Click;
                }
            }
        }

		static void btn_Click(object sender, EventArgs e)
		{
			System.Media.SystemSounds.Beep.Play();
		}
 
Share this answer
 
Comments
akosisugar 3-Dec-17 6:51am    
im calling the method in form_load event.. your code doesnt work
________________ 3-Dec-17 8:39am    
I call setButtons(Form f) from constructor of form:


public partial class Form2 : Form
{

public Form2(object dataToShow)
{
InitializeComponent();
//dataGridView1.DataSource = dataToShow;
setButtons(this);
}


public static void setButtons(Form f)
{
foreach (Control c in f.Controls)
{
Button btn = c as Button;

if (c == btn)
{
btn.Click += btn_Click;
}
}
}

static void btn_Click(object sender, EventArgs e)
{
System.Media.SystemSounds.Beep.Play();
}


}

Do you understand what is event in .NET?


________________ 3-Dec-17 8:48am    
You can call the "setButtons(Form f)" from any place, but you should send as parameter correct form. This is the point. In my example, I send "this" from form constructor, so it sure will be correct object.
akosisugar 3-Dec-17 10:20am    
yess i do understand event..

sorry sorry.. its working now..
________________ 4-Dec-17 2:09am    
All ok. In C++ it was pointer to function, simple 32 bit integer (address in memory), in In .NET it almost the same, but better protected(by name and parameters).
So, event in class is collection (may be null if empty) of "pointers to function".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900