I had to build a application to exercise and test several web services. I created a form for each web service and used text boxes, combo boxes, and date pickers to fill in properties for the class used in the web service parameters. Eventually I had several test forms and started with the common method of starting multiple forms:
private void buttonTestUI01_Click(object sender, EventArgs e)
{
TestUI01Form f = new TestUI01Form();
f.Show();
}
private void buttonTestUI02_Click(object sender, EventArgs e)
{
TestUI02Form f = new TestUI02Form();
f.Show();
}
However I wanted a different mechanism that would allow me to add more test forms in the future. I used a List<> variable to hold the forms and used Activator.Instantiate to create the forms. Here is the implementation:
public partial class TestForm : Form
{
// Test UI Forms
private List<Form> MyForms;
public TestForm()
{
InitializeComponent();
MyForms = new List<Form>();
}
private Form MyForm_Create(Type MyFormType)
{
Form f = null;
int emptyIndex = -1;
// Find instance of form in list
for (int i = 0; i < MyForms.Count; ++i)
{
f = MyForms[i];
if (f == null)
emptyIndex = i;
else if (f.GetType() == MyFormType)
{
if (f.WindowState == FormWindowState.Minimized)
f.WindowState = FormWindowState.Normal;
f.Activate();
break;
}
f = null;
}
// Create new instance of form
if (f == null)
{
f = (Form) Activator.CreateInstance(MyFormType);
f.Disposed += new EventHandler(MyForm_Disposed);
if (emptyIndex >= 0)
MyForms[emptyIndex] = f;
else
MyForms.Add(f);
}
f.Show();
return f;
}
private void MyForm_Disposed(object sender, EventArgs e)
{
Form f = null;
for (int i = 0; i < MyForms.Count; ++i)
{
f = MyForms[i];
if (f == sender)
{
f = null;
MyForms[i] = null;
}
}
}
private void buttonTestUI01_Click(object sender, EventArgs e)
{
Form f = MyForm_Create(typeof(TestUI01Form));
f.Show();
}
}
This implementation is still not ideal as I have used a different button for each test form. Ultimately I will abstract the implementation even more extensible and use a dynamic menu or array of buttons so I don't have to code a handler for each button. Hopefully I'll get a chance to do that soon.