2012-12-09 135 views
1

我还在学习面向对象。我目前正试图制作一个电影票亭,其中您点击您喜欢的电影海报按钮。 Form1是其中显示3个按钮的主菜单形式,其名称如下movibutton1,movibutton2,movibutton3。所以基本上我想隐藏Form1,只要点击一个按钮,但按钮的事件处理程序位于另一个类中。我希望事件处理程序留在班上。是否可以在事件处理程序中关闭窗体,其中事件处理程序在类中?

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     buttonPosters(); 
    } 
    private void buttonPosters() 
    { 
     derClassForForm1 classForm1 = new derClassForForm1(); 
     moviButton1.Click += new EventHandler(classForm1.movPosterClicked); 
     moviButton2.Click += new EventHandler(classForm1.movPosterClicked); 
     moviButton3.Click += new EventHandler(classForm1.movPosterClicked); 
    } 
} 

public class derClassForForm1 
{ 
    public void movPosterClicked(object sender, EventArgs e) 
    { 
     Button posterClick = (Button)sender; 
     if (posterClick.Name.Equals("moviButton1")) 
     { 
      Mov1 movie = new Mov1(); 
      Form2 movPoster = new Form2(movie.movTitle(), movie.movSynop(), movie.movImagesrc()); 
      movPoster.Show(); 
     } 
     else if (posterClick.Name.Equals("moviButton2")) 
     { 
      Mov2 movie = new Mov2(); 
      Form2 movPoster = new Form2(movie.movTitle(), movie.movSynop(), movie.movImagesrc()); 
      movPoster.Show(); 
     } 
     else if (posterClick.Name.Equals("moviButton3")) 
     { 
      Mov3 movie = new Mov3(); 
      Form2 movPoster = new Form2(movie.movTitle(), movie.movSynop(), movie.movImagesrc()); 
      movPoster.Show(); 
     } 

     //wanted to have like a form.hide() here 
    } 
} 

回答

0

你可以一个公共属性,以你derClassForForm1类为这样的补充:

public Form ParentForm {get; set;} 

然后,你可以修改你的代码的方法buttonPosters

private void buttonPosters() 
{ 
    derClassForForm1 classForm1 = new derClassForForm1(); 
    classForm1.ParentForm = this; 
    moviButton1.Click += new EventHandler(classForm1.movPosterClicked); 
    moviButton2.Click += new EventHandler(classForm1.movPosterClicked); 
    moviButton3.Click += new EventHandler(classForm1.movPosterClicked); 
} 

这将使你在movPosterClicked的末尾写下这样的内容:

if(this.ParentForm != null) 
{ 
    this.ParentForm.Hide(); 
}