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

博客介绍了在.NET中实现应用程序只能运行一个实例的方法。主要使用Mutex实现进程间同步,给出了具体的代码示例,包括判断是否为首个实例、运行应用程序等功能,还展示了具体的使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前在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());
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值