標籤:
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#的應用程式只被開啟一次