当前位置: 首页 > article >正文

C# 确保程序只有一个实例运行

常规需求 C#程序只能运行一次,不能多开:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace BallLocation
{
    static class Program
    {
        [STAThread]
        static void Main()
        { 
            bool createNew;
            using (Mutex mutex = new Mutex(true, Application.ProductName, out createNew))
            {
                if (createNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                    //这里是 winform的入口
				}
				 else
                {
                    MessageBox.Show("程序已经在运行,请不要重复打开!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
			}	
		}
	}
}

            //使用System.Threading.Mutex来确保程序只有一个实例运行
            //Application.ProductName可能不是最佳选择,因为它依赖于Application类的初始化
            //建议使用一个固定的字符串作为互斥体名称

		   bool createNew;
		   using (Mutex mutex = new Mutex(true, "Global\\BallLocationMutex", out createNew))
           {
               if (createNew)
               {
                   Application.EnableVisualStyles();
                   Application.SetCompatibleTextRenderingDefault(false);
                   Application.Run(new MainForm());
               }
               else
               {
                   // 如果程序已经在运行,提示用户
                   MessageBox.Show("程序已经在运行,请不要重复打开!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
               }
           }
//----------
string currentDirectory = Environment.CurrentDirectory;
Console.WriteLine("当前工作目录: " + currentDirectory);


http://www.kler.cn/a/564444.html

相关文章:

  • shell脚本的相关练习--->分支结构---->循环结构
  • yolo11 training benchmark [i7-13700 vs nvidia 3090]
  • Staruml软件的介绍安装uml类图的绘制流程
  • 第8章:流式海啸:数据重构
  • 8、HTTP/1.0和HTTP/1.1的区别【高频】
  • information_schema.processlist 表详解
  • Stale file handle
  • TCP 缓冲区核心机制
  • 为什么要进行软件测试?
  • 前端或者后端通常用到数组使用方式
  • 华为对流程认知的三个层次(重新认识流程)
  • 执行git操作时报错:`remote: [session-b8xxxda3] Access denied ...`解决方案
  • 深度分析:AheadComputing的RISC-V技术背景、战略定位与挑战
  • VScode在windows10上使用clang-format
  • 《Python实战进阶》专栏 No 5:GraphQL vs RESTful API 对比与实现
  • Spark基础篇-Application、Job、Stage 和 Task
  • StrokesPlus【电脑鼠标键盘手势软件】v0.5.8.0 中文绿色便携版
  • Scrapy:隧道代理中移除 Proxy-Authorization 的原理解析
  • 基于微信小程序的校园社团管理系统
  • 高效部署:Windows 系统下 Sentinel 安装与配置全攻略