zoukankan      html  css  js  c++  java
  • WinForm 窗体中实现单例模式

    方式一: 单进程的实现

    View Code
     1    static class Program
     2     {
     3         /// <summary>
     4         /// 应用程序的主入口点。
     5         /// </summary>
     6         [STAThread]
     7         static void Main()
     8         {
     9             Application.EnableVisualStyles();
    10             Application.SetCompatibleTextRenderingDefault(false);
    11             
    12             //获取当前进程名称
    13             string currentProcessName = Process.GetCurrentProcess().ProcessName;
    14 
    15             //把该名称的所有进程的列表
    16             Process[] process = Process.GetProcessesByName(currentProcessName);
    17 
    18             if (process.Length > 1)
    19             {
    20                 MessageBox.Show("程序已经运行");
    21                 return;
    22             }
    23             Application.Run(new ThMain());
    24         }
    25     }

    方式二:窗体单例模式的实现

     public static Form1 thMian = null;
    
     /// <summary>
            /// 获取单个实例
            /// </summary>
            /// <returns></returns>
            public static Form1 GetInstance()
            {
                if (thMian == null || thMian.IsDisposed == true)  //newForm.IsDisposed == true必需,否则会出现“访问已释放资源”的异常
                {
                    thMian = new Form1();
                }
                else
                {
                    thMian.Activate();
                }
                return thMian;
            }
    
    调用:
      GetInstance();
      thMian.Show();
    

      

  • 相关阅读:
    twfont
    判断数组中某个元素的个数
    vue swiper中的大坑
    this指向问题
    vue.nextTick简单的用法
    类图解析
    设计模式
    设计模式
    Http Notes
    VS Notes
  • 原文地址:https://www.cnblogs.com/blosaa/p/3068437.html
Copyright © 2011-2022 走看看