通过主窗口按钮关闭窗体/窗口C#

时间:2015-10-27 21:18:25

标签: c# forms

我想请求大家的帮助。当我按.button上的Main Window时,我想要做的是关闭随机加载的窗口。这是我今天的窗口名称是( im1,im2,im3,im4)。正如预期的那样,所有窗口都将在加载时打开,但是在我的代码中某处是错误的,当我按下按钮时,非打开窗口将被关闭。另外,我想要一个non-repeating随机代码。因此,如果我再次单击该按钮,那将是100%确定它不会尝试关闭已经关闭的窗口。希望你理解我的英语我很抱歉。

     public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        Random g = new Random();
       int ans = g.Next(1, 5);
        if (ans == 1)
        {
            im1 v1 = new im1();
            v1.Close();       
        }
        if (ans == 2)
        {
            im2 v2 = new im2();
            v2.Close();
        }
        if (ans == 3) 
        {
            im3 v3 = new im3();
            v3.Close();
        }
        if (ans == 4)
        {
            im4 v4 = new im4();
            v4.Close();

        }

    }

    private void Window_Loaded_1(object sender, RoutedEventArgs e)
    {
        im4 v4 = new im4();
        v4.Show();
        im3 v3 = new im3();
        v3.Show();
        im2 v2 = new im2();
        v2.Show();        
        im1 v1 = new im1();
        v1.Show();
    }
}

}

1 个答案:

答案 0 :(得分:1)

字段是实例成员,它们是可以从类的每个方法访问的变量。

正如M.kazem Akhgary建议的那样,你的代码看起来像这样:

public partial class MainWindow : Window
{
    im1 v1 = null;
    im2 v2 = null;
    im3 v3 = null;
    im4 v4 = null;

    public MainWindow()
    {
        InitializeComponent();
    }
    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        Random g = new Random();
       int ans = g.Next(1, 5);
        if (ans == 1)
        {
            v1.Close();       
        }
        if (ans == 2)
        {
            v2.Close();
        }
        if (ans == 3) 
        {
            v3.Close();
        }
        if (ans == 4)
        {
            v4.Close();
        }
    }

    private void Window_Loaded_1(object sender, RoutedEventArgs e)
    {
        v4 = new im4();
        v4.Show();
        v3 = new im3();
        v3.Show();
        v2 = new im2();
        v2.Show();        
        v1 = new im1();
        v1.Show();
    }
}