我正在尝试使用此处概述的方法构建单实例应用程序。
我尝试使用该解决方案的原因是我需要将命令行从第二次尝试启动应用程序传递到第一个实例,这似乎是实现这一目标的最简单方法。
我需要支持的操作系统风格:
- 视窗 XP SP3
- 视窗 7 32 位
- 视窗 7 64 位
我已经让它在所有三个操作系统版本上都可以工作,但是,我有一台装有 Windows 7 32Bit 的机器,它会因 CantStartSingleInstanceException而崩溃。
这是代码:
SingleInstanceController.cs:
using System;
using Microsoft.VisualBasic.ApplicationServices;
namespace SingleInstanceTest
{
public class SingleInstanceController : WindowsFormsApplicationBase
{
public SingleInstanceController()
{
IsSingleInstance = true;
}
protected override void OnCreateMainForm()
{
base.OnCreateMainForm();
Form1 f = new Form1();
MainForm = f;
// process first command line
f.SetCommandLine(Environment.GetCommandLineArgs());
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
Form1 f = MainForm as Form1;
// process subsequent command lines
f.SetCommandLine(eventArgs.CommandLine);
}
}
}
程序.cs:
using System;
using System.Windows.Forms;
namespace SingleInstanceTest
{
static class Program
{
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SingleInstanceController si = new SingleInstanceController();
// This triggers the crash on one machine when starting the
// app for the second time
si.Run(Environment.GetCommandLineArgs());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
// this is triggered with CantStartSingleInstanceException
MessageBox.Show(e.ToString(),"ThreadException");
MessageBox.Show(e.Exception.ToString(), "ThreadException");
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show(e.ToString(), "UnhandledException");
MessageBox.Show(e.ExceptionObject.ToString(), "UnhandledException");
}
}
}
出于测试目的,该表单只是一个包含显示命令行参数的列表框的普通表单。
任何想法为什么这不能在那台机器上工作?搞了这两天,搞不懂。。。