【C#】 实现WinForm中只能启动一个实例
如代码所示:
方法一:
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; namespace ProcessBarTest { static class Program { private const int SW_SHOW = 5; [DllImport("User32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Process p = RunningInstance(); if (p == null) { Application.Run(new MainForm()); } else { HandleRunningInstance(p); } } /// <summary> /// Get current process /// </summary> /// <returns></returns> private static Process RunningInstance() { Process currentProcess = Process.GetCurrentProcess(); Process[] processByName = Process.GetProcessesByName(currentProcess.ProcessName); return processByName.FirstOrDefault(process2 => (process2.Id != currentProcess.Id) && (Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == currentProcess.MainModule.FileName)); } private static void HandleRunningInstance(Process p) { MessageBox.Show("已经有一个实例在运行,一台电脑只能运行一个实例!"); ShowWindowAsync(p.MainWindowHandle, SW_SHOW); } } }
方法二:
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Threading; using System.Reflection; namespace LANChat_UI { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool bIsRunning; Mutex mutexApp = new Mutex(false, Assembly.GetExecutingAssembly().FullName, out bIsRunning); if (!bIsRunning) { MessageBox.Show("聊天程序正在运行,系统只能运行一个聊天实例!"); } else { MainForm mainForm = new MainForm(); mainForm.Text = Environment.UserName.ToString(); Application.Run(mainForm); } } } }