C#实现让程序只能打开一个实例(总结3方法)(转)

我个人感觉用判断进程法比较好一点,当然这只是我个人观点

本文转自龙族

 

 

用c#开发应用程序.有时候只需要让程序打开后不能被再次打开..只能打开一次..
总结出有3个方法可实现..如果还有什么好的方法请大家一起来讨论下..

 

                        //=====创建互斥体法:=====
            //bool blnIsRunning;
            //Mutex mutexApp = new Mutex(false, Assembly.GetExecutingAssembly().FullName, out   blnIsRunning);
            //if (!blnIsRunning)
            //{
            //    MessageBox.Show("程序已经运行!", "提示",
            //    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //    return;
            //}   

 

 

 

                        //保证同时只有一个客户端在运行   
            //System.Threading.Mutex mutexMyapplication = new System.Threading.Mutex(false, "OnePorcess.exe");
            //if (!mutexMyapplication.WaitOne(100, false))
            //{
            //    MessageBox.Show("程序" + Application.ProductName + "已经运行!", Application.ProductName,
            //    MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}

 

 

//=====判断进程法:(修改程序名字后依然能执行)=====
            //Process current = Process.GetCurrentProcess();
            //Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //foreach (Process process in processes)
            //{
            //    if (process.Id != current.Id)
            //    {
            //        if (process.MainModule.FileName
            //        == current.MainModule.FileName)
            //        {
            //            MessageBox.Show("程序已经运行!", Application.ProductName,
            //            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //            return;
            //        }
            //    }
            //}     

 

只需要把需要的方法代码放在Void Main()方法中就可以实现..

 

posted @ 2009-01-27 00:14  梅林听风  阅读(1637)  评论(0编辑  收藏  举报