Posted on 2007-06-17 13:13
玄铁剑 阅读(288)
评论(0) 编辑 收藏 引用 所属分类:
windows
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());
}
}
}
另一方法
/////////////
System.Threading.Mutex appSingleton = new System.Threading.Mutex(false, "MyProgInstance_PPP");
if(appSingleton.WaitOne(0, false))
{
Application.Run(new FormMain(););
}
else
{
MessageBox.Show("程序已经运行");
}