子夜

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在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
   {
    //退出运行。因为已经有一个实例运行了。
   }

posted on 2011-04-01 16:01  子夜  阅读(420)  评论(0)    收藏  举报