2012-12-10 25 views
2

我想关闭动态创建的形式与动态按钮(这是我的工作中最简单的,我也添加其他按钮来做其他工作,但我想这是一个很好的开始的地方)。
截至目前,我可以为该按钮创建窗体,按钮和点击事件,但我不知道在click事件函数中添加什么来关闭该按钮的主机。我猜我可以以某种方式通过点击功能访问按钮父母?或者可能传递窗体控件作为函数中的参数?任何帮助表示赞赏!关闭动态创建的形式与动态按钮

 //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(); 

而且我的点击事件功能看起来非常正常:

void saveButton_buttonClick(object sender, EventArgs e) 
    { 


    } 

不幸的是,我不知道是什么,增加了对功能的工作!预先感谢任何人可以帮助我的帮助!我觉得这应该是一个直接的问题来解决,但我一直没能弄清楚......

回答

3

虽然这当然可以用命名函数做到这一点,但通常使用在案件匿名函数是这样的:

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(); 
+0

精彩。这实际上更符合我的目的。感谢帮助! – tmwoods

1

的简单方法是使用lambda方法:

Button exitButton = new Button(); 
exitButton.Text = "Exit"; 
exitButton.Click += (s, e) => { shapshot.Close(); };