我有一个类,创建了一个带有几个按钮的表单实例。我在这个类中有一个函数,旨在等待用户点击其中一个按钮,并根据按下的按钮返回不同的值。我已经阅读了一些关于使用匿名委托的东西,但我不确定我如何确定哪个具体的按钮被按下。我的原始方法是创建一个自定义事件,将按钮编号作为参数传递,并从我的类中附加一个事件处理程序,但我不确定一旦进入委托,我该如何使该函数返回任何内容。
有没有简单直接的方法来做到这一点?
有没有简单直接的方法来做到这一点?
public class MyForm : Form
{
// form initialization, etc, etc.
public Button Button1
{
get { return button1; }
}
}
public class MyClass
{
public Form CreateForm()
{
var form = new MyForm();
form.Button1.Click += HandleButton1Clicked;
return form;
}
private void HandleButton1Clicked(object sender, EventArgs e)
{
// do whatever you need to do when Button1 is clicked
}
}
或者,您可以将ButtonClicked事件添加到窗体中,并以此确定按下了哪个按钮。 窗体将订阅每个按钮的Click事件,并使用button作为发送者触发ButtonClicked。
我可能会选择前者,因为它避免了编写if语句来确定按下了哪个按钮。
编辑以适应评论中的工作流程:
在这种情况下,您可以让窗体为您处理一些细节。 例如,让窗体记录按下了哪个按钮。 如果将窗体显示为模态对话框,则按设计将阻止创建窗体的函数,直到其被关闭。
public class MyForm : Form
{
// form initialization, etc, etc.
private Button button1;
private Button button2;
public MyForm()
{
InitializeComponent();
button1.Click += HandleButtonClicked;
button1.DialogResult = DialogResult.OK;
button2.Click += HandleButtonClicked;
button2.DialogResult = DialogResult.OK;
}
private void HandleButtonClicked(object sender, EventArgs e)
{
ButtonClicked = sender as Button;
}
public Button ButtonClicked
{
get; private set;
}
}
调用代码:
public class MyClass
{
public int GetValue()
{
var form = new MyForm();
if(form.ShowDialog() == DialogResult.OK) // this will block until form is closed
{
// return some value based on form.ButtonClicked
// adjust method's return type as necessary
}
else
{
// do something if the user closed the form without
// clicking on one of the buttons
}
}
}