using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace 全自动水压检测仪.DATA { /// /// 基于单例模式的WinForm窗口管理器 /// 提供流畅的窗口切换API /// public sealed class FormManager { // 单例实例 private static readonly Lazy _instance = new Lazy(() => new FormManager()); // 存储所有窗口实例 private readonly Dictionary _formInstances = new Dictionary(); // 私有构造函数,防止外部实例化 private FormManager() { } /// /// 获取单例实例 /// public static FormManager Instance => _instance.Value; /// /// 注册窗口实例 /// /// 窗口类型 /// 窗口实例 /// 返回自身,支持链式调用 public FormManager RegisterForm(T formInstance) where T : Form { Type formType = typeof(T); if (!_formInstances.ContainsKey(formType)) { _formInstances[formType] = formInstance; // 监听窗口关闭事件,自动移除注册 formInstance.FormClosed += (s, e) => _formInstances.Remove(formType); } return this; } /// /// 显示指定窗口并隐藏当前活动窗口 /// /// 要显示的窗口类型 /// 返回自身,支持链式调用 public FormManager SwitchTo() where T : Form { Type targetType = typeof(T); // 检查目标窗口是否已注册 if (!_formInstances.TryGetValue(targetType, out Form targetForm)) { throw new InvalidOperationException($"窗口 {targetType.Name} 未注册,请先调用 RegisterForm 方法"); } // 隐藏当前活动窗口 Form activeForm = Form.ActiveForm; if (activeForm != null && activeForm != targetForm) { activeForm.Hide(); } // 显示目标窗口并置于顶层 targetForm.Show(); targetForm.BringToFront(); return this; } /// /// 显示指定窗口 /// /// 要显示的窗口类型 /// 返回自身,支持链式调用 public FormManager ShowForm() where T : Form { Type targetType = typeof(T); if (_formInstances.TryGetValue(targetType, out Form targetForm)) { targetForm.Show(); targetForm.BringToFront(); } return this; } /// /// 隐藏指定窗口 /// /// 要隐藏的窗口类型 /// 返回自身,支持链式调用 public FormManager HideForm() where T : Form { Type targetType = typeof(T); if (_formInstances.TryGetValue(targetType, out Form targetForm)) { targetForm.Hide(); } return this; } /// /// 获取已注册的窗口实例 /// /// 窗口类型 /// 窗口实例 public T GetForm() where T : Form { Type targetType = typeof(T); if (_formInstances.TryGetValue(targetType, out Form form)) { return form as T; } return null; } } }