目录
方法一:
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Process[] processes = Process.GetProcesses();
Process currentProcess = Process.GetCurrentProcess();
bool processExist = false;
foreach (Process p in processes)
{
if (p.ProcessName == currentProcess.ProcessName && p.Id != currentProcess.Id)
{
processExist = true;
}
}
if (processExist)
{
Application.Exit();
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
string processName = Process.GetCurrentProcess().ProcessName;
Process[] processes = Process.GetProcessesByName(processName);
//如果该数组长度大于1,说明多次运行
if (processes.Length > 1)
{
MessageBox.Show("程序已运行,不能再次打开!");
Environment.Exit(1);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
方法二:
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
bool isAppRunning = false;
Mutex mutex = new Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out isAppRunning);
if (!isAppRunning)
{
MessageBox.Show("程序已运行,不能再次打开!");
Environment.Exit(1);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
本文介绍两种防止Windows Form应用程序被多次启动的方法:一种是通过检查当前运行进程来阻止程序重复开启;另一种是利用Mutex互斥对象实现单一实例运行。这两种方法能够有效避免同一程序的多个实例同时运行。
1123

被折叠的 条评论
为什么被折叠?



