using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace ShangHaiElectricalLine.Tool
{
public static class SingleInstanceHelper
{
/// <summary>
/// 检查当前程序是否已存在运行实例(基于进程名)。
/// 如果已存在,则提示用户并关闭当前实例。
/// </summary>
/// <returns>如果当前是唯一实例,返回 true;否则返回 false 并自动退出。</returns>
public static bool EnsureSingleInstance()
{
try
{
string moduleName = Process.GetCurrentProcess().MainModule?.ModuleName;
if (string.IsNullOrEmpty(moduleName))
return true; // 无法获取模块名,保守起见允许运行
string processName = Path.GetFileNameWithoutExtension(moduleName);
Process[] processes = Process.GetProcessesByName(processName);
if (processes.Length > 1)
{
MessageBox.Show("请勿重复运行!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
Application.Current?.Shutdown();
return false;
}
return true;
}
catch (Exception ex)
{
// 可选:记录异常或忽略(例如权限不足访问 MainModule)
// MessageBox.Show($"检测单实例时发生错误:{ex.Message}", "错误");
return true; // 出错时默认允许运行,避免误杀
}
}
}
}
如何使用这个方法
public partial class App : Application
{
public App()
{
// 在构造函数中检查单实例
if (!SingleInstanceHelper.EnsureSingleInstance())
{
// 如果已有实例,直接退出
// EnsureSingleInstance已经显示提示并调用Environment.Exit
return;
}
}
}




