多例模式,保证实例的唯一性,仅适用于form窗体

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PubClass
{
    /// <summary>
    /// 文件名:PublicClass
    /// 文件功能描述:同一界面某些共同操作的类
    /// 版权所有:Copyright (C)
    /// 创建日期:2013.8.7
    /// 创建人:李东波
    /// 修改日期:2013.08.21
    /// 修改描述:添加窗体多例模式控制
    public class SingleForm
    {
       
        
        /// <summary>
        /// 多例模式,保证实例的唯一性,仅适用于form窗体
        /// </summary>
        /// <typeparam name="T">窗体实例类型</typeparam>
        /// <param name="tag">占用窗体的tag属性,并且存储区分标识</param>
        /// <returns>成功返回true,失败返回false,失败后需要之后的程序创建窗体,并给窗体tag保存区分标识</returns>
        public static bool ActivateForm<T>(string tag) where T : System.Windows.Forms.Form
        {
            try
            {
                if (Application.OpenForms.Count > 0)
                {
                    foreach (var item in Application.OpenForms)
                    {
                        if (item.GetType().Equals(typeof(T)))
                        {
                            T adt = item as T;
                            if (adt.Tag != null && adt.Tag.ToString().Equals(tag))
                            {
                                adt.Activate();
                                return true;

                            }
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
               //throw new Exception(ex.Message);
                return false;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/goto/p/3443320.html