C#中只運行一個實例的方法

在Main函數之前添加如下代碼,引入kernel32.dll裏的函數:
/// <summary>
  /// 應用程序的主入口點。只運行一個實例
  /// </summary>
  [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;  

然後在Main函數裏調用如下:
//***********只運行一個實例*********************************************
   IntPtr   hMutex;  
   hMutex = CreateMutex(null,false,"test");  
   if  ( GetLastError() != ERROR_ALREADY_EXISTS)  
   { 進行其它操作  }
   else
   {
    //退出運行。因爲已經有一個實例運行了。
   } 

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