亲宝软件园·资讯

展开

WinForm单例窗体 WinForm单例窗体用法实例

HTL 人气:0
想了解WinForm单例窗体用法实例的相关内容吗,HTL在本文为您仔细讲解WinForm单例窗体的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:WinForm,单例窗体,下面大家一起来学习吧。

本文实例讲述了WinForm单例窗体。分享给大家供大家参考,具体如下:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
namespace Common
{
  /// <summary>
  /// 窗体的单例模式
  /// </summary>
  /// <typeparam name="T"></typeparam>
  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>
    /// <param name="obj"></param>
    /// <param name="args"></param>
    private static void Display(object obj, FormClosedEventArgs args)
    {
      form = null;
      list.Remove(form);
    }
    /// <summary>创建新窗体
    /// </summary>
    private static void CreateNewForm(T t1)
    {
      form = t1;
      form.FormClosed += new FormClosedEventHandler(Display);//订阅窗体的关闭事件,释放对象
    }
    /// <summary>
    /// 是否存在该窗体
    /// </summary>
    /// <param name="T1"></param>
    /// <returns></returns>
    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;
    }
  }
}

调用如下:

不带参数的构造函数

Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer());
customer.MdiParent = this;//Mdi窗体
customer.WindowState = FormWindowState.Maximized;//最大化
customer.Show();
customer.Activate();

带参数的构造函数

Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer(customerid));
customer.MdiParent = this;
customer.WindowState = FormWindowState.Maximized;
customer.Show();
customer.Activate();

希望本文所述对大家C#程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论