C#以不同的形式设置所有按钮 [英] C# setting up all buttons in different forms
本文介绍了C#以不同的形式设置所有按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将我的公共方法用于每个表单。我想要的是当方法被调用时,找到表格中的所有按钮并在点击时在每个按钮中播放系统声音。
我是什么尝试过:
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();
}
}
}
推荐答案
你需要使用控件的InvokeRequired
属性,请参阅:
如何:对Windows窗体控件进行线程安全调用Microsoft Docs [ ^ ]
You need to use the control'sInvokeRequired
property, see:
How to: Make Thread-Safe Calls to Windows Forms Controls | Microsoft Docs[^]
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();
}
这篇关于C#以不同的形式设置所有按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文