using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using WcfControlMonitorLib; using System.Threading; using System.Diagnostics; using System.Runtime.InteropServices; using WcfControlMonitorWebLib; using System.Security.Policy; using System.Threading.Tasks; namespace wcfControlMonitorClient { /// /// 应用程序唯一运行实例实现 /// 即当前系统只能打开一个SiasunLMS程序实例 /// public static class SingleInstance { /// /// 获得正在运行的程序实例线程 /// public static Process GetRunningInstance() { Process currentProcess = Process.GetCurrentProcess(); //获取当前进程 //获取当前运行程序完全限定名 string currentFileName = currentProcess.MainModule.FileName; //获取进程名为ProcessName的Process数组。 Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName); //遍历有相同进程名称正在运行的进程 foreach (Process process in processes) { if (process.MainModule.FileName == currentFileName) { if (process.Id != currentProcess.Id) //根据进程ID排除当前进程 return process;//返回已运行的进程实例 } } return null; } //接下来调用两个WinAPI,其功能将在包装方法中描述, [DllImport("User32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); [DllImport("User32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); //定义类成员辅助变量 private const int WS_SHOWNORMAL = 1; /// /// 对其进一步包装,HandleRunningInstance静态方法为获取应用程序句柄,设置应用程序为前台运行,并返回bool值。 /// /// 进程实例 public static bool HandleRunningInstance(Process instance) { //确保窗口没有被最小化或最大化 ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //设置为foreground window return SetForegroundWindow(instance.MainWindowHandle); } /// /// 判断是否实例是否存在 /// public static bool HandleRunningInstance() { Process p = GetRunningInstance(); if (p != null) { HandleRunningInstance(p); return true; } return false; } } static class Program { public static FrmHost mainForm = null; /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new FrmHost()); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (Process p =SingleInstance.GetRunningInstance()) { try { if (p != null) //已经有应用程序副本执行 { System.Windows.Forms.MessageBox.Show("请检查程序是否已经隐藏在后台运行!", "系统提示"); p.Dispose(); } else { WebHost.Startup("http://127.0.0.1:8088"); //WebHost.Startup("http://192.168.16.3:8088"); mainForm = new FrmHost(); Application.Run(mainForm); } } catch (Exception ex) { MessageBox.Show(ex.Message + ex.InnerException, "", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } }