常规需求 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);