使应用程序只能运行单个实例。

王朝c#·作者佚名  2006-12-17
窄屏简体版  字體: |||超大  

使应用程序只能运行单个实例。

使应用程序只能运行单个实例。 以前在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- 王朝網路 版權所有 導航