2011-10-12 114 views
0
FormCollection fc = Application.OpenForms; 

foreach (Form frm in fc) 
{ 
//iterate through 
} 

ORC#如何检查形式已经在紧凑的框架

Form fc = Application.OpenForms["FORMNAME"]; if (fc != null) fc.Close(); fm.Show(); 

但这种非紧凑框架3.5厂开放。我如何检查表格是否已经在CF 3.5中打开?

回答

2

正如@巴里写道,你将不得不自己做。最简单的方法是使用字典。您的密钥可以是表单的类型,名称或任何您需要的。

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; 
} 

或者,如果你想支持多种格式类型,并希望避免铸造,使用一般方法:

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; 
} 

有两种通用的重载。其中之一是用这样的:

// use this if MyFormType has a parameterless constructor 
var form = CreateOrShow<MyFormType>("Form1"); 

,或者,如果你需要初始化过程中的参数传递到您的形式:

// use this if MyFormType accepts parameters in constructor 
var form = CreateOrShow<MyFormType>("Form1",() => new MyFormType(someData)); 
+0

变种form =(PregledZaslonov)Forms.CreateOrShow(“PregledZaslonov”); form.Show();或者如果我使用泛型方法,我总是得到InvalidCastException。为什么? – senzacionale

+0

@senzacionale:对不起,我现在就修复它。 – Groo

+0

@senzacionale:好的,完成。问题出现在'f = new Form();'行,因为它总是实例化一个基本的'Form'实例,而不是''T'泛型类。如果您还需要在施工过程中提供参数,我添加了一个额外的过载。 – Groo

1

Compact Framework中不存在Application.OpenForms集合。

您将不得不推出自己的收藏品并以这种方式跟踪它们。

nice tutorial here解释如何实现这一点。

0

你可能对您的所有形式的静态布尔字段。然后,您必须创建一对方法来切换它,并将打开和关闭事件处理程序绑定到它。诚然,这不是最优雅的解决方案。

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; 
    } 
} 

要么或者使某个形式的集合,每一次形式加载,使其存储对自身的引用它,并反复针对检查的形式是开/存在