zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    Vue 3 组件开发:搭建基于SpreadJS的表格编辑系统(环境搭建)
    纵观 ActiveX 平台的兴衰史,看开发控件的技术演变
    mysql函数
    SQL Server 连接字符串和身份验证
    http Content type
    C中二叉排序树的非递归和递归插入操作以及中序遍历代码实现【可运行】
    带头结点和不带头结点的链栈基本操作
    小程序开发日记-14悼篮球兄弟
    小程序开发日记-13 NetworkTimeout
    小程序开发日记-12 SSL证书及相关
  • 原文地址:https://www.cnblogs.com/shaozhuyong/p/5238306.html
Copyright © 2011-2022 走看看