WinForm 使用互斥锁防止应用重复打开

参考

环境

软件/系统 版本 说明
Windows windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器
Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.14.17
.NET Framework 4.8

正文

Program.cs 添加如下代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace XiaqiuchuProgram
{
    internal static class Program
    {

        // 唯一标识
        private const string MutexName = "xiaqiuchu_cnblogs";

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // 创建互斥体(initialOwner: true 表示当前进程初始拥有该互斥体)
            using (Mutex mutex = new Mutex(true, MutexName, out bool createdNew))
            {
                if (createdNew)
                {
                    // 互斥体是新创建的,说明程序未运行,正常启动
                    Application.Run(new MainFormView());
                }
                else
                {
                    // 互斥体已存在,说明程序已启动,提示用户并激活已有窗口
                    MessageBox.Show("程序已在运行中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
}

posted @ 2025-11-16 09:34  夏秋初  阅读(20)  评论(0)    收藏  举报