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


    保证只运行一个应用程序的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);
        }
    }
  • 相关阅读:
    js中变量声明提前
    冒泡与捕获
    win7安装不了nodejs及解决方法
    nodejs配置app的服务
    Ming Rpc
    test
    Java8 Lambda sample (iwantmoon.com出品)
    Spring Mvc 输出Json(iwantmoon.com出品)
    单点登录(iwantmoon.com出品)
    虚拟机WIN10发布.NetCore 3.1
  • 原文地址:https://www.cnblogs.com/shaozhuyong/p/5238306.html
Copyright © 2020-2023  润新知