C# 函数检查程序是否正在运行

// 该C#代码使用.net8 WinForm

using System.Diagnostics;

namespace OnlyOne
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) // 加载窗口执行
        {
            // Process1(); 
            // Process2();
        }

        // 判断当前进程 1
        static void Process1() 
        {
            //获取欲启动进程名
            string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            ////获取版本号 
            //CommonData.VersionNumber = Application.ProductVersion; 
            //检查进程是否已经启动,已经启动则显示报错信息退出程序。 
            if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
            {
                MessageBox.Show("程序已经运行!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Application.Exit();
                //Application.ExitThread();
                return;
            }

        }

        // 判断当前进程 2
        static void Process2() 
        {
            var selfname = System.AppDomain.CurrentDomain.FriendlyName;  // 获取当前exe名称.
            Process[] processes = Process.GetProcessesByName(selfname);  // 获取进程组是否有该进程, 返回进程数组
            Form1 form = new Form1();
            if (processes.Length == 0)
            {
                form.textBox1.Text = "not runing";
            }
            else
            {
                form.textBox1.Text = "runing";
            }
        }
        
         static void OnlyOne()          // 推荐使用该方法
        {
             bool Exist;                         // 定义一个bool变量, 判断程序是否已在运行
             Mutex mutex = new Mutex(true, "仅一次", out Exist);                          // 创建一个Mutex互斥对象
             if (Exist)
                {                                                                                      
                    mutex.ReleaseMutex();                                            // 如果没有运行
                }
                else
                {
                    MessageBox.Show("仅能运行一次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Close();
                }
        } 
    }
}

 

posted @ 2024-03-24 08:03  edolf  阅读(29)  评论(0编辑  收藏  举报