让我们看一下下面的代码,我在其中创建了一个按钮列表。
List<System.Windows.Forms.Button> buttons = new List<System.Windows.Forms.Button>();
for(int i = 0; i < 5; i++) {
buttons.Add( System.Windows.Forms.Button>() );
buttons[i].Name = "button_" + i.ToString();
this.Controls.Add(buttons[i]);
buttons[i].Click += new System.EventHandler(this.Bt_windowClick);
}
下一部分是我感到困惑的地方。当调用此委托(delegate)时,我希望它告诉我实际单击了哪个按钮。我该怎么做?
void Bt_windowClick(object sender, EventArgs e)
{
// I would like to get the name of the button that was clicked
}
在此先感谢您的支持!
最佳答案
Sender 对象是一个按钮,它引发了事件。因此,只需将其转换为 Button
类型:
void Bt_windowClick(object sender, EventArgs e)
{
Button button = (Button)sender;
// use button
MessageBox.Show(button.Name);
}
关于c# - 如何管理在运行时创建的 WinForms 按钮的委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13444877/