public static Process GetExistProcess() { Process currentProcess = Process.GetCurrentProcess(); // 当前程序 foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName)) { if (process.Id != currentProcess.Id) // 找到其他同名进程 { return process; // 返回已运行的进程 } } return null; // 没有其他实例 }2. 主程序入口
static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 堆代码 duidaima.com var runningProcess = GetExistProcess(); if (runningProcess != null) // 如果有实例运行 { IntPtr mainWindowHandle = runningProcess.MainWindowHandle; if (mainWindowHandle == IntPtr.Zero) // 窗口被隐藏 { mainWindowHandle = FindWindow(null, "唯一程序"); } ShowWindowAsync(mainWindowHandle, 1); // 显示窗口 SetForegroundWindow(mainWindowHandle); // 置于前台 } else { Application.Run(new MainForm()); // 启动新实例 } } }3. Win32 API 调用
[DllImport("User32.dll", EntryPoint = "FindWindow")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll ")] public static extern bool SetForegroundWindow(IntPtr hWnd);FindWindow: 根据窗口名称查找窗口句柄。
SetForegroundWindow: 将窗口设置为前台窗口。
static Mutex mutex = new Mutex(true, "UniqueAppName", out bool createdNew); if (!createdNew) { // 已经有实例运行 return; }2.窗口句柄缓存