我更喜欢类似于以下的互斥解决方案.这样,如果应用程序已经加载,它会重新关注应用程序
using System.Threading; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); ////// The main entry point for the application. /// [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; } } } } }
强制只运行.net(C#)中程序的一个实例,在program.cs文件中使用此代码:
public static Process PriorProcess() // Returns a System.Diagnostics.Process pointing to // a pre-existing process with the same name as the // current one, if any; or null if the current process // is unique. { Process curr = Process.GetCurrentProcess(); Process[] procs = Process.GetProcessesByName(curr.ProcessName); foreach (Process p in procs) { if ((p.Id != curr.Id) && (p.MainModule.FileName == curr.MainModule.FileName)) return p; } return null; }
以及如下:
[STAThread] static void Main() { if (PriorProcess() != null) { MessageBox.Show("Another instance of the app is already running."); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); }
这是我在我的应用程序中使用的:
static void Main() { bool mutexCreated = false; System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated ); if( !mutexCreated ) { if( MessageBox.Show( "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?", "slimKEYS already running", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) != DialogResult.Yes ) { mutex.Close(); return; } } // The usual stuff with Application.Run() mutex.Close(); }