首页 > 代码库 > 如何确保C#的应用程序只被打开一次
如何确保C#的应用程序只被打开一次
http://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows
using System.Threading;[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)]static extern bool SetForegroundWindow(IntPtr hWnd);/// <summary>/// The main entry point for the application./// </summary>[STAThread]static void Main(){ bool createdNew = true; using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } }}
上面代码的MyApplicationName需要确保是唯一识别的,使用Process.GetCurrentProcess().MainModule.FileName提示说找不到文件
http://stackoverflow.com/questions/4313756/creating-a-mutex-throws-a-directorynotfoundexception
My mutex name had \
in it, which windows was interpreting as a path character. Running:
将路径名中的反斜杠替换成_就可以了
坑爹的是又出现新问题
问题1:
bool createdNew;
string appName;
appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
appName = @"Local\" + appName; //Local\ZITaker
using (Mutex mutex = new Mutex(true, appName, out createdNew))
此段代码的问题在于,两个程序的Assembly.GetExecutingAssembly().GetName().Name会是一致的
问题2:
bool createdNew;
string appName;
appName = Process.GetCurrentProcess().MainModule.FileName;
appName = @"Local\" + appName;
using (Mutex mutex = new Mutex(true, appName, out createdNew))
这个会提示未能找到路径
正确的做法:
string appName;
appName = Process.GetCurrentProcess().MainModule.FileName;
appName = appName.Replace(Path.DirectorySeparatorChar, ‘_‘);
using (Mutex mutex = new Mutex(true, appName, out createdNew))
如何确保C#的应用程序只被打开一次