Winform 只运行一个实例 代码

    技术2026-04-25  6

    using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Net; using System.Xml; using System.Runtime.InteropServices; using System.Diagnostics; using System.Reflection; namespace AutoUpdaterDemo { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Process instance = RunningInstance(); //创建系统进程的实例 //判断该实例是否已经正在运行 if (instance == null) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //运行登录窗体 Application.Run(new Form1()); } else { HandleRunningInstance(instance); //显示正在运行的实例到前端窗口 } } /// <summary> /// 只运行一个实例 /// </summary> /// <returns></returns> private static Process RunningInstance() { Process current = Process.GetCurrentProcess(); //获取当前实例 Process[] processes = Process.GetProcessesByName(current.ProcessName); //获取进程的名称 foreach (Process process in processes) { if (process.Id != current.Id) { if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName) { return process; //返回进程 } } } return null; } private static void HandleRunningInstance(Process instance) { MessageBox.Show("该应用系统已经在运行!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //调用api函数,正常显示窗口 SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端。 } [DllImport("User32.dll")] private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow); [DllImport("User32.dll")] private static extern bool SetForegroundWindow(System.IntPtr hWnd); private const int WS_SHOWNORMAL = 1; } }  

    最新回复(0)