使应用程序只运行单个实例(C#)
代码如下:(在类中)
public partial class AppSingleton : Form
{
public AppSingleton()
{
InitializeComponent();
}
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();
}
}
主程序中(main)需要做如下修改:
{
public AppSingleton()
{
InitializeComponent();
}
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();
}
}
主程序中(main)需要做如下修改:
AppSingleton.Run(new AppSingleton());
//Application.Run(new AppSingleton());
//Application.Run(new AppSingleton());
没有评论:
发表评论