C# WinForm 通用单例窗体模式实现
在 Windows Forms 应用程序开发中,管理多个同类型窗口的打开状态是一个常见需求。本文提供了一种基于泛型的 WinForm 单例窗体解决方案,通过封装静态方法来实现窗体实例的唯一性控制,支持带参数和无参数的构造函数调用。
核心原理
实现 WinForm 单例窗体的核心在于利用静态变量缓存当前激活的窗体实例,并通过检查现有窗体列表来决定是复用还是新建窗口。本方案采用泛型 T 限制传入的类型必须继承自 Form 且具备无参构造函数,从而保证了类型安全与灵活性。
第1步:添加单例管理器代码
目的:创建可复用的通用单例类,处理窗体的创建、查找及生命周期释放。
操作:将以下代码添加至项目的公共命名空间(如 Common)或新建文件。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Common
{
/// <summary>
/// 窗体的单例模式
/// </summary>
public class FormSingle<T> where T : Form, new()
{
private static T form;
private static IList<T> list { get; set; }
public static T GetForm(T t1)
{
// 检查是否存在该类型的窗体实例
if (!IsExist(t1))
{
CreateNewForm(t1);
}
return form;
}
/// <summary>
/// 当关闭窗体时执行清理工作
/// </summary>
private static void Display(object obj, FormClosedEventArgs args)
{
form = null;
if (list != null)
list.Remove((T)obj);
}
/// <summary>
/// 初始化新的窗体实例并注册关闭事件
/// </summary>
private static void CreateNewForm(T t1)
{
form = t1;
// 订阅窗体关闭事件,以便再次打开时可以重新创建
form.FormClosed += new FormClosedEventHandler(Display);
}
/// <summary>
/// 根据窗体文本判断是否已存在
/// </summary>
private static bool IsExist(T T1)
{
if (list == null)
{
list = new List<T>();
list.Add(T1);
return false;
}
// 如果已有窗体的标题与新传入的一致,则视为同一个窗体
foreach (var t in list)
{
if (t.Text == T1.Text)
return true;
}
list.Add(T1);
return false;
}
}
}
实际应用场景
第2步:无参构造函数调用
入口:MdiParent 父窗体或任意触发事件的方法。
动作:实例化目标窗体并将其作为参数传入 GetForm。该方法会返回已存在的实例或新创建的实例。
关键点:务必设置 MdiParent、WindowState 等属性后调用 Show() 和 Activate() 以确保显示效果。
// 假设 Customer.AddCustomer 是你需要管理的窗体
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer());
customer.MdiParent = this; // 设置为当前 MDI 容器
customer.WindowState = FormWindowState.Maximized; // 最大化窗口
customer.Show();
customer.Activate(); // 激活窗口获取焦点
第3步:带参构造函数调用
场景:当窗体需要在打开时接收特定数据(如 ID)时,使用带参构造函数。
动作:同样调用 GetForm,但在传入的新建对象中传递必要的参数。
// 传入 customerid 参数
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer(customerid));
customer.MdiParent = this;
customer.WindowState = FormWindowState.Maximized;
customer.Show();
customer.Activate();
总结
通过使用 FormSingle<T> 泛型类,你可以轻松地在 WinForm 应用中控制同类窗体的唯一性。其逻辑依赖于窗体文本匹配以及关闭事件的清理机制。在实际使用中,需注意若窗体内容完全依赖参数而非标题区分,可能需要修改 IsExist 方法的比较逻辑以适应更复杂的场景。
以上就是 C# WinForm 单例窗体模式实现的详细内容,更多关于 C# 窗体管理与设计模式的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













