避免重複打開程序

方法來源於網路

方法1:    
  public   static   void   Main(string[]   args)    
  {  
    //聲明互斥體  
    System.Threading.Mutex   mutex   =   new   System.Threading.Mutex(false,   "ThisShouldOnlyRunOnce");  
    //判斷互斥體是否使用中  
    bool   Running   =   !mutex.WaitOne(0,   false);  
    if   (!   Running)  
      Application.Run(new   FormMain());  
    else  
      MessageBox.Show("程序已經啓動!");  
  }  
   
     
   
  方法2:  
   
  //添加引用  
  using   System.Runtime.InteropServices;  
   
  //申明  
  [StructLayout(   LayoutKind.Sequential)]  
  public   class   SECURITY_ATTRIBUTES    
  {  
    public   int   nLength;    
    public   int   lpSecurityDescriptor;    
    public   int   bInheritHandle;    
  }  
  [System.Runtime.InteropServices.DllImport("kernel32")]  
  private   static   extern   int   GetLastError();   [System.Runtime.InteropServices.DllImport("kernel32")]  
  private   static   extern   IntPtr   CreateMutex(SECURITY_ATTRIBUTES   lpMutexAttributes,bool   bInitialOwner,string   lpName);   [System.Runtime.InteropServices.DllImport("kernel32")]  
  private   static   extern   int   ReleaseMutex(IntPtr   hMutex);  
  const   int   ERROR_ALREADY_EXISTS   =   0183;  
   
  //調用    
  static   void   Main()    
  {  
    IntPtr   hMutex;  
    hMutex=CreateMutex(null,false,"test");  
    if   (GetLastError()!=ERROR_ALREADY_EXISTS)  
    {  
        Application.Run(new   Form1());  
    }  
    else  
    {  
        MessageBox.Show("本程序只允許同時運行一個");  
        ReleaseMutex(hMutex);  
    }  
  } 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章