C#通过使用Microsoft.VisualBasic.ApplicationServices类库实现单实例运行
VB.net 通过简单的属性配置,就能实现单实例运行,非常简单
但在 C# 中,天生不支持单实例运行,如果想要单实例,处理起来很复杂。
如:查找进程信息、线程同步等,实现起来稍显麻烦
但是通过使用VB.Net的类库,可以方便的解决这个问题
先引用 using Microsoft.VisualBasic.ApplicationServices;
具体的示例代码如下:
============================================================================
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SingleInstanceManager manager = new SingleInstanceManager();//单实例管理器
manager.Run(new string[]{});
//Application.Run(new frmMain()); //屏蔽掉以前的加载头
}
// Using VB bits to detect single instances and process accordingly:
// * OnStartup is fired when the first instance loads
// * OnStartupNextInstance is fired when the application is re-run again
// NOTE: it is redirected to this instance thanks to IsSingleInstance
public class SingleInstanceManager : WindowsFormsApplicationBase
{
frmMain app;
public SingleInstanceManager()
{
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
// First time app is launched
//app = new SingleInstanceApplication();
//app.Run();
app = new frmMain();//改为自己的程序运行窗体
Application.Run(app);
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
// Subsequent launches
base.OnStartupNextInstance(eventArgs);
app.Activate();
MessageBox.Show(Application.ProductName + " 已经在运行了,不能重复运行。", "确定", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);//给个对话框提示
}
}
}