首先我的代码如下:
bool isExist;
Mutex MyMutex = new Mutex(true,"MySoft",out isExist);
if (isExist)
...{
//程序运行
Application.Run(new MainForm());
}
else
...{
//show ErrorMessage Application terminate
}
好好的代码在"debug"模式下正常运行,呵呵,运行的挺美~
要发布了,把配置改为"release",把生成中的调试信息改为"none"(.net2003的发布根本不用改)
结果:哇!~互斥不起做用了,把"release"模式下的调试信息改为"full",互斥有起作用了,不知道为什么,
但是觉得平白多个pdb文件,很不舒服~
最后从网上找了点资料整理出来,贡献出来:
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
private const int WS_SHOWNORMAL = 1;
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public static Process RunningInstance()
...{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
...{
//Ignore the current process
if (process.Id != current.Id && Assembly.GetExecutingAssembly().Location.Replace("/", "/") == current.MainModule.FileName)
return process;
}
return null;
}
public static bool HandleRunningInstance(Process instance)
...{
instance.WaitForInputIdle();
//确保窗口没有被最小化或最大化
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
//设置真实例程为foreground window
return SetForegroundWindow(instance.MainWindowHandle);
}
[STAThread]
static void Main(string[] args)
...{
Process MYSoft = RunningInstance();
if(MYSoft ==null)
...{
//启动程序
}
else
...{
//激活已启动的程序
HandleRunningInstance(MYSoft);
}
}
本文探讨了一个关于Mutex在Debug模式下正常工作但在Release模式下失效的问题,并提供了一种解决方案,通过检查进程实例来避免应用程序多次运行。

735

被折叠的 条评论
为什么被折叠?



