新增的Application.OpenForms属性
窗体布局:
然后代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FormCollection
{
public partial class frmMain : Form
{
private int nNumber = 1;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
RefreshListBox();
}
private void button1_Click(object sender, EventArgs e)
{
Form form = new Form();
form.Name = nNumber.ToString();
form.Text = nNumber.ToString();
form.Show();
nNumber++;
RefreshListBox();
}
private void button2_Click(object sender, EventArgs e)
{
if (-1 == listBox1.SelectedIndex)
{
return;
}
Application.OpenForms[listBox1.Items[listBox1.SelectedIndex].ToString()].Close();
RefreshListBox();
}
private void RefreshListBox()
{
listBox1.Items.Clear();
foreach (Form form in Application.OpenForms)
{
listBox1.Items.Add(form.Name);
}
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FormCollection
{
public partial class frmMain : Form
{
private int nNumber = 1;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
RefreshListBox();
}
private void button1_Click(object sender, EventArgs e)
{
Form form = new Form();
form.Name = nNumber.ToString();
form.Text = nNumber.ToString();
form.Show();
nNumber++;
RefreshListBox();
}
private void button2_Click(object sender, EventArgs e)
{
if (-1 == listBox1.SelectedIndex)
{
return;
}
Application.OpenForms[listBox1.Items[listBox1.SelectedIndex].ToString()].Close();
RefreshListBox();
}
private void RefreshListBox()
{
listBox1.Items.Clear();
foreach (Form form in Application.OpenForms)
{
listBox1.Items.Add(form.Name);
}
}
}
}