C#代码实现, 确保windows程序只有1个实例(instance)

解决方案 »

  1.   

    使用单例模式即可
    class Singleton
    { private static Singleton singleton = new Singleton();
             //私有的构造函数
    private Singleton(){}
    public static Singleton GetInstance()
    {
                  return singleton;
    }
    }
      

  2.   

    public static Process RunningInstance()  
    {  
         Process current = Process.GetCurrentProcess(); 
         Process[] processes = Process.GetProcessesByName (current.ProcessName); 
          //Loop through the running processes in with the same name 
     
          foreach (Process process in processes) 
           {  
              //Ignore the current process 
                if (process.Id != current.Id) 
               { 
                    //Make sure that the process is running from the exe file. 
                     if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) 
                     { 
                         //Return the other process instance. 
                         return process; 
                     } 
                } 
           } 
           //No other instance was found, return null. 
           return null; 
     }