用动态按钮关闭动态创建的表单 [英] Close dynamically created form with dynamic button
问题描述
我正试图用动态按钮关闭一个动态创建的表单(这是我最简单的工作,我也添加了其他按钮来执行其他工作,但我认为这是一个很好的开始)。
到目前为止,我可以为该按钮创建表单,按钮和点击事件,但是我不知道在点击事件功能中添加什么来关闭该按钮的主机。我猜想我可以通过点击功能访问按钮的父母?或者可以通过表单控件作为函数中的参数?任何帮助是赞赏!
I'm trying to close a dynamically created form with a dynamic button (this is the simplest of my jobs, I am also adding other buttons to do other jobs but I figured this is a good place to start).
As of now I can create the form, button and the click event for that button, but I don't know what to add within the click event function to close the host of that button. I am guessing I can somehow access the buttons parent through the click function? Or maybe pass the form control as an argument in the function? Any help is appreciated!
//Create form
Snapshot snapshot = new Snapshot();
snapshot.StartPosition = FormStartPosition.CenterParent;
//Create save button
Button saveButton = new Button();
saveButton.Text = "Save Screenshot";
saveButton.Location = new Point(snapshot.Width - 100, snapshot.Height - 130);
saveButton.Click += new EventHandler(saveButton_buttonClick);
//Create exit button
Button exitButton = new Button();
exitButton.Text = "Exit";
exitButton.Location = new Point(snapshot.Width - 100, snapshot.Height - 100);
//Add all the controls and open the form
snapshot.Controls.Add(saveButton);
snapshot.Controls.Add(exitButton);
snapshot.ShowDialog();
我的点击事件功能看起来很正常:
And my click event function looks pretty much normal:
void saveButton_buttonClick(object sender, EventArgs e)
{
}
不幸的是,我不知道添加什么功能的工作!提前感谢有人可以给我的帮助!我觉得这应该是一个直截了当的问题要解决,但我无法弄清楚...
Unfortunately I don't know what to add for the function to work! Thanks in advance for any help someone can give me! I feel like this should be a straight-forward problem to solve but I haven't been able to figure it out...
推荐答案
p>尽管使用一个命名函数可以做到这一点,但在这种情况下只需使用匿名函数通常更简单:
While it's certainly possible to do this with a named function, it's generally simpler to just use an anonymous function in cases like this:
Snapshot snapshot = new Snapshot();
snapshot.StartPosition = FormStartPosition.CenterParent;
//Create save button
Button saveButton = new Button();
saveButton.Text = "Save Screenshot";
saveButton.Location = new Point(snapshot.Width - 100, snapshot.Height - 130);
saveButton.Click += (_,args)=>
{
SaveSnapshot();
};
//Create exit button
Button exitButton = new Button();
exitButton.Text = "Exit";
exitButton.Location = new Point(snapshot.Width - 100, snapshot.Height - 100);
exitButton.Click += (_,args)=>
{
snapshot.Close();
};
//Add all the controls and open the form
snapshot.Controls.Add(saveButton);
snapshot.Controls.Add(exitButton);
snapshot.ShowDialog();
这篇关于用动态按钮关闭动态创建的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!