C#簡單的防止程序運行多個實例的方法
程序员文章站
2022-05-24 09:17:59
...
簡單的程序防重複運行
必須加入的命名空間
using System.Reflection;
using System.Threading;
/// <summary>
/// 方法一:創建互斥體法,根據名稱判斷是否運行
/// </summary>
private void Form1_Load(object sender, EventArgs e)
{
bool create;
Mutex m = new Mutex(false, Assembly.GetExecutingAssembly().FullName, out create);
if (!create)
{
MessageBox.Show("軟件已經運行", "系統提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
this.Close();
return;
}
}
/// <summary>
/// 方法二:根據名稱判斷是否運行
/// </summary>
private void Mutex2()
{
System.Threading.Mutex mutexMyapplication = new Mutex(false, "exerepeat.exe");
if (!mutexMyapplication.WaitOne(100,false))
{
MessageBox.Show("程序已經運行", "系統提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
this.Close();
return;
}
}
/// <summary>
/// 方法三:通過進程名稱判斷是否運行
/// </summary>
private void Mutex3()
{
Process currentpro = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentpro.ProcessName);
foreach (var item in processes)
{
if (item.Id!=currentpro.Id)
{
if (item.MainModule.FileName==currentpro.MainModule.FileName)
{
MessageBox.Show("程序已經運行","系統提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning);
this.Close();
return;
}
}
}
}
推荐阅读