使应用程序只能运行单个实例
使应用程序只能运行单个实例
以前在vb中要防止应用程序运行多个实例的方式很简单,判断app.previnstance 就可以了。 来看一下.net中是如何实现的,主要使用mutex来实现进程间同步 using System;using System.Threading;using System.Windows.Forms;using System.Runtime.InteropServices;namespace LogisticsSystem{ /// <summary> /// 使应用程序只能运行一个实例 的摘要说明。 /// </summary> public class AppSingleton { static Mutex m_Mutex; public static void Run() { if(IsFirstInstance()) { Application.ApplicationExit = new EventHandler(OnExit); Application.Run(); } } public static void Run(ApplicationContext context) { if(IsFirstInstance()) { Application.ApplicationExit = new EventHandler(OnExit); Application.Run(context); } } public static void Run(Form mainForm) { if(IsFirstInstance()) { Application.ApplicationExit = new EventHandler(OnExit); Application.Run(mainForm); } else { MessageBox.Show("应用程序已启动,请在任务管理中关闭后再启动!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning); } } static bool IsFirstInstance() { m_Mutex = new Mutex(false,"SingletonApp Mutext"); bool owned = false; owned = m_Mutex.WaitOne(TimeSpan.Zero,false); return owned ; } static void OnExit(object sender,EventArgs args) { m_Mutex.ReleaseMutex(); m_Mutex.Close(); } }} 具体使用是如下 using System;using System.Drawing;using System.Windows.Forms;namespace LogisticsSystem{ /// <summary> /// MainClass 的摘要说明。 /// </summary> public class MainClass { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { AppSingleton.Run(new mainForm()); //Application.Run(new mainForm()); } }} (2005-11-01:09:02)
| 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。 |