通过主窗口按钮C#关闭窗体/窗口
本文关键字:窗口 窗体 按钮 | 更新日期: 2023-09-27 18:19:26
我想请求大家的帮助。每当我按下Main Window
上的.button
时,我想做的是关闭一个随机加载的窗口。这是我今天所在的位置,窗口名称为( 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();
}
}
}
字段是实例成员,它们是可以从类的每个方法访问的变量。
正如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();
}
}