C# JabLib系列之如何保证只运行一个应用程序的实现

时间:2022-08-29 07:53:59

保证只运行一个应用程序的C#实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;

namespace JackLib.App
{
    static class Program {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main() {
            try {
                //只运行一个实例
                Process instance = GetExecutingInstance();
                if (instance == null) {
                    //设置样式
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    //运行控制端
                    Application.Run(new FrmMain());
                }
                else {
                    //cmdShow 1:恢复正常大小窗口 2 最小化窗口 3 最大化窗口
                    ShowWindowAsync(instance.MainWindowHandle, 3);
                    //最前端显示
                    SetForegroundWindow(instance.MainWindowHandle);
                }
            }
            catch (Exception ex) {
                Console.Write(ex);
            }
        }

        /// <summary>
        /// 获取当前程序正在运行的进程,没有运行进程返回null
        /// </summary>
        /// <returns></returns>
        private static Process GetExecutingInstance() {
            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;
        }

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);
    }
}