我们说我有两种形式。当我按下第一个按钮时,会显示第二个按钮。但是我希望能够通过按下它上面的按钮来关闭第二个但是它应该在第一个关闭第二个窗口的方法上解除一个方法。必须使用代表和事件来完成。我该怎么做?谢谢你的帮助。
答案 0 :(得分:0)
你的问题不是那么清楚......可能对你有帮助。
// Form1 is the 1st form or main form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//creat a sample object of FormEXt
var form = new FormExt();
//subscribe its CustomClose Event
form.CustomClose += new FormExt.CloseMeDelegate(form_CustomClose);
//set the text
form.Text = "Samplee 01";
//show the form
form.Show();
//repeat a again
form = new FormExt();
form.CustomClose += new FormExt.CloseMeDelegate(form_CustomClose);
form.Text = "Samplee 02";
form.Show();
}
void form_CustomClose(Form form)
{
//get the form show the titile
MessageBox.Show("Going to Close" + form.Text);
//close the form
form.Close();
}
}
//second form with a button
public class FormExt : Form
{
//creat a delegate which takes form as input
public delegate void CloseMeDelegate(Form form);
//creat event from delegeate set it fake delegate in order to avoid null excpetion
public event CloseMeDelegate CustomClose = delegate {
};
public FormExt() {
//creat a button
var button = new Button() { Text = "Click" , Top = 10 , Left=10 };
//grab button click event
button.Click += delegate
{
//invoke custome close event
CustomClose(this);
};
//add button on the form
this.Controls.Add(button);
}
}
答案 1 :(得分:0)
在第二个窗口中,声明每当窗口要发出关闭时引发的事件:
// ## Second window ##
public delegate void IssueCloseDelegate(object sender, EventArgs e);
public event IssueCloseDelegate IssueClose;
按下关闭按钮时,请举起以下事件:
// ## Second window, button click handler
if (IssueClose != null)
IssueClose(this, EventArgs.Empty);
在第一个窗口中实例化窗口时,注册事件并处理它:
// ## First window ##
//some method
var newWindow = new SecondWindow();
newWindow.IssueClose += NewWindow_IssueClose;
newWindow.Show();
//...
private void NewWindow_IssueClose(object sender, EventArgs e)
{
var closedWindow = (SecondWindow)sender;
closedWindow.Close();
}