如何显示WinForm应用已存在的隐藏/最小化实例?
.NET 5/.NET Core WinForm 单实例激活已运行窗口方案
你当前的进程检测逻辑已经能识别到已运行的实例,但要激活并显示最小化/隐藏的窗口,需要借助Windows原生API实现。以下是完整的修正代码:
首先添加Windows API的导入声明:
using System; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using System.IO; using System.Reflection; public static class NativeMethods { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); // 窗口恢复命令(针对最小化状态) public const int SW_RESTORE = 9; // 窗口显示命令(针对隐藏状态) public const int SW_SHOW = 5; }
然后修改Main方法的逻辑:
[STAThread] static void Main() { string processName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); var runningProcesses = Process.GetProcessesByName(processName); // 排除当前进程,精准定位已运行的实例 var existingProcess = runningProcesses.FirstOrDefault(p => p.Id != Process.GetCurrentProcess().Id); if (existingProcess != null) { // 恢复最小化窗口,若窗口为隐藏状态则替换为SW_SHOW NativeMethods.ShowWindowAsync(existingProcess.MainWindowHandle, NativeMethods.SW_RESTORE); // 将窗口带到前台确保用户可见 NativeMethods.SetForegroundWindow(existingProcess.MainWindowHandle); return; } // 无已运行实例时启动新窗口 Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyGUI()); }
关键说明:
- 排除当前进程:原逻辑用
runningProcess.Length>1判断,但GetProcessesByName会包含刚启动的当前进程,通过FirstOrDefault(p => p.Id != Process.GetCurrentProcess().Id)能精准定位到已运行的目标实例。 - 适配不同窗口状态:
ShowWindowAsync配合SW_RESTORE可恢复最小化窗口;若窗口是隐藏状态,将参数替换为SW_SHOW即可显示窗口。 - 确保窗口前置:
SetForegroundWindow能将目标窗口带到系统前台,让用户立即看到。
内容的提问来源于stack exchange,提问作者skm
相关产品推荐
相关产品推荐

