c# how check if the form is already open in compact framework
FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
//iterate through
}
OR
Form fc = 开发者_如何学编程Application.OpenForms["FORMNAME"]; if (fc != null) fc.Close(); fm.Show();
but non of this works in compact framework 3.5. How can i check if form is already opened in CF 3.5?
As @Barry wrote, you will have to do it yourself. Easiest way is to use a dictionary. Your key can be a form's type, its name, or whatever you need.
private static readonly Dictionary<string, MyForm> _dict
= new Dictionary<string, MyForm>();
public MyForm CreateOrShow(string formName)
{
Form f = null;
if (!_dict.TryGetValue(formName, out f))
{
f = new MyForm();
_dict.Add(formName, f);
}
return f;
}
Or, if you want to support multiple form types and want to avoid casting, use a generic method:
private static readonly Dictionary<string, Form> _dict
= new Dictionary<string, Form>();
public T CreateOrShow<T>(string formName) where T : Form, new()
{
Form f = null;
if (!_dict.TryGetValue(formName, out f))
{
f = new T();
_dict.Add(formName, f);
}
return (T)f;
}
public T CreateOrShow<T>(string formName, Func<T> ctor) where T : Form
{
Form f = null;
if (!_dict.TryGetValue(formName, out f))
{
f = ctor();
_dict.Add(formName, f);
}
return (T)f;
}
There are two generic overloads. One of them is used like this:
// use this if MyFormType has a parameterless constructor
var form = CreateOrShow<MyFormType>("Form1");
or, if you need to pass parameters to your form during init:
// use this if MyFormType accepts parameters in constructor
var form = CreateOrShow<MyFormType>("Form1", () => new MyFormType(someData));
The Application.OpenForms
collection doesn't exist in the Compact Framework.
You would have to roll your own collection and keep track of them that way.
There is nice tutorial here that explains how to achieve this.
You could have a static boolean field on all your forms. Then you'd have to create a couple methods to toggle it, and bind the Opening and Closing event handlers to it. Not the most elegant solution admittedly.
partial class Form1 : Form
{
static bool IsFormOpen;
public Form1()
{
InitializeComponent();
this.Load += SignalFormOpen;
this.FormClosing += SignalFormClosed;
}
void SignalFormOpen(object sender, EventArgs e)
{
IsFormOpen = true;
}
void SignalFormClosed(object sender, EventArgs e)
{
IsFormOpen = false;
}
}
Either that or make a collection of forms somewhere, and each time a form loads make it store a reference to itself in it, and iterate against that to check if the form is open/exists
精彩评论