2012-12-09 182 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(); 
}