【发布时间】:2018-05-29 13:20:29
【问题描述】:
我使用 .net 4.5 和 Main 类上的互斥锁开发了一个单实例 WinForm 应用程序。一些用户报告他们无法启动应用程序,因为互斥锁已被占用。
static string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value + "-OrientalWave";
public static string GUID { get { return guid; } }
[STAThread]
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
// Single Instance Check
bool createdNew;
using (var mutex = new Mutex(true, guid, out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length > 0)
{
string filename = args[0];
Application.Run(new frmMain(filename));
}
else
Application.Run(new frmMain());
}
else
{
if (args.Length > 0)
{
// If i want to open a file
string filename = args[0];
NamedPipesClient pipeClient = new NamedPipesClient();
pipeClient.Start();
pipeClient.SendMessage(filename);
pipeClient.Stop();
}
else
MessageBox.Show("Only single instance allowed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
try
{
var exception = (Exception)args.ExceptionObject;
MessageBox.Show(exception.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error);
Logger.Write(Logger.LogType.Error, exception.Source, "Message: " + exception.Message + " - Stack: " + exception.StackTrace);
}
catch { }
Environment.Exit(0);
}
我在网上搜索了创建单实例应用程序的解决方案或替代方法,但没有成功。
【问题讨论】:
-
你把它作为你的应用程序的一个功能,所以并不奇怪。请避免重新发明这个轮子,它已经得到框架的支持。永远青睐那些被数十万程序员抨击、每天被测试数百万次的代码。 stackoverflow.com/a/29260770/17034
-
在我看来,这段代码应该能按预期工作......