C#建立了一个windows程序,如何防止多个程序实例运行?有什么技巧吗?
C#建立了一个windows程序,如何防止多个程序实例运行?有什么技巧吗?
------解决方案--------------------static void Main() 
         { 
             Application.EnableVisualStyles(); 
             Application.SetCompatibleTextRenderingDefault(false); 
             #region Check the application whether running 
             Process process = RunningInstance(); 
             if (process != null) 
             { 
                 MessageBox.Show( "This application is already running. ", ResourceString.AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); 
                 return; 
             } 
             #endregion   
                     Application.Run(new MainForm()); 
         } 
         //不允许有两个程序同时启动 
         public static Process RunningInstance() 
         { 
             Process current = Process.GetCurrentProcess(); 
             Process[] processes = Process.GetProcessesByName(current.ProcessName); 
             //遍历正在有相同名字运行的例程  
             foreach (Process process in processes) 
             { 
                 //忽略现有的例程  
                 if (process.Id != current.Id) 
                 { 
                     //确保例程从EXE文件运行  
                     if (Assembly.GetExecutingAssembly().Location.Replace( "/ ",  "\\ ") == 
                          current.MainModule.FileName) 
                     { 
                         //返回另一个例程实例  
                         return process; 
                     } 
                 } 
             } 
             //没有其它的例程,返回Null  
             return null; 
         }
------解决方案--------------------我在这篇文章中介绍了三种实现方式, 
 http://blog.csdn.net/zhzuo/archive/2006/06/30/857405.aspx 
 http://blog.csdn.net/zhzuo/archive/2006/07/04/874745.aspx 
------解决方案--------------------在main函数中加入如下 
 bool bCreatedNew; 
 Mutex m =new Mutex( false,  "你的程序名 ", out bCreatedNew ); 
 if( bCreatedNew ) 
 Application.Run(new Form1());   
 =============================================================== 
 我就用这个的,还有一个是检测是否存在同路径下的同进程名的方法,但是效率比较低,而且麻烦
------解决方案--------------------回复人:junsheng(月生) ( 一级(初级)) 信誉:99 	2007-1-19 15:19:37 	得分:0 
 在main函数中加入如下 
 bool bCreatedNew; 
 Mutex m =new Mutex( false,  "你的程序名 ", out bCreatedNew ); 
 if( bCreatedNew ) 
 Application.Run(new Form1());   
 -------------------> > > >  
 以上方法可行,也最簡單,樓主可以使用.