C# 程序重复启动,将程序显示到最前

时间:2024-04-12 13:14:59
/// <summary> /// 进程辅助助手,检查程序是否重复启动, /// 重复启动的话,就将上一个程序显示出来到UI上面 /// </summary> public class ProcessHelper { /// <summary> /// 命名互斥体 /// </summary> public static Mutex mutex; /// <summary> /// 给定一个唯一的name值,检查程序是否重复启动 /// </summary> /// <param name="name"></param> /// <returns></returns> public static bool CheckProgramRepeat() { // 获取当前进程的 Process 实例 Process currentProcess = Process.GetCurrentProcess(); // 获取当前进程的名称 string processName = currentProcess.ProcessName; mutex = new Mutex(true, processName, out bool createNew); if (!createNew) { ShowProcess(currentProcess); return true; } return false; } [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] static extern bool IsIconic(IntPtr hWnd); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); const int SW_RESTORE = 9; /// <summary> /// 显示程序 /// </summary> public static void ShowProcess(Process currentProcess) { // 已经有一个实例在运行,找到并将其窗口置于前台 foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName)) { if (process.Id != currentProcess.Id) { IntPtr mainWindowHandle = process.MainWindowHandle; // 检查窗口是否最小化,如果是,则恢复窗口 if (IsIconic(mainWindowHandle)) { ShowWindow(mainWindowHandle, SW_RESTORE); } SetForegroundWindow(process.MainWindowHandle); break; } } } }

相关文章