是否可以关闭事件处理程序中的窗体,其中事件处理程序位于类中



我还在学习OOP。我目前正在尝试制作一个电影票亭,您可以在其中单击您喜欢的电影海报的按钮。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
    }
}

你可以像这样向类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();
}

相关内容

  • 没有找到相关文章

最新更新