C# winform判断自身程序是否已运行,如果已运行则激活窗体

C# winform判断自身程序是否已运行,如果已运行则激活窗体

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

namespace WindowsFormsApp1
{
   
    internal static class Program
    {
   
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
   
            Process currentProcess = Process.GetCurrentProcess();

            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
            if (processes.Length > 1)
            {
   
                //MessageBox.Show("此软件已经在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                IntPtr handle = GetOldProcess(processes, currentProcess).MainWindowHandle;
                SwitchToThisWindow(handle, true);    // 激活,显示在最前  

                Thread.Sleep(1000);
                Environment.Exit(1);
            }



            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        /// <summary>
        /// 获取老的进程
        /// </summary>
        /// <param name="processes"></param>
        /// <returns></returns>
        private static Process GetOldProcess(Process[] processes, Process currentProcess)
        {
   
            //遍历与当前进程名称相同的进程列表
            foreach (Process process in processes)
            {
   
                //如果实例已经存在则忽略当前进程
                if (process.Id != currentProcess.Id)
                {
   
                    //返回已经存在的进程
                    return process;
                }
            }
            return null;
        }
    }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-12 20:20:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-12 20:20:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-12 20:20:03       82 阅读
  4. Python语言-面向对象

    2024-01-12 20:20:03       91 阅读

热门阅读

  1. 【力扣每日一题】力扣2707字符串中的额外字符

    2024-01-12 20:20:03       59 阅读
  2. 自定义Flink SourceFunction定时读取数据库

    2024-01-12 20:20:03       56 阅读
  3. 学习使用php、js脚本关闭当前页面窗口的方法

    2024-01-12 20:20:03       58 阅读
  4. Wine源码中添加新的DLL模块

    2024-01-12 20:20:03       61 阅读
  5. SpringBoot 配置文件

    2024-01-12 20:20:03       44 阅读
  6. Springboot 中接口服务重试机制

    2024-01-12 20:20:03       42 阅读
  7. 博客随手记

    2024-01-12 20:20:03       55 阅读