(引用了 Microsoft.VisualBasic.ApplicationServices)
SingleInstanceApplicationWrapper.cs
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace Highflyer
{
/// <summary>
/// 单实例应用程序封装类
/// </summary>
public class SingleInstanceApplicationWrapper : WindowsFormsApplicationBase
{
private readonly Form mainForm;
public SingleInstanceApplicationWrapper(Form form)
{
mainForm = form;
#if DEBUG
this.IsSingleInstance = false;
#endif
#if RELEASE
this.IsSingleInstance = true;
#endif
}
protected override bool OnStartup(StartupEventArgs e)
{
Application.Run(mainForm);
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
{
// 这里可以把本次使用的参数传给之前的实例,本人在一个WPF 屏幕键盘项目里传送了键盘显示方式(数字、英文、手写)参数
//e.BringToForeground = true;
//if (e.CommandLine.Count > 0)
//{
// app.DealArgs(e.CommandLine.ToArray());
//}
}
}
}
Program.cs
using System;
using System.Windows.Forms;
using Highflyer;
namespace Eparcar.ParkLocal.GateBoxClient
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm mainForm = new MainForm();
SingleInstanceApplicationWrapper wrapper = new SingleInstanceApplicationWrapper(mainForm);
wrapper.Run(args);
}
}
}