[C#.NET][VB.NET][VB6] 如何禁止程式重覆執行 / System.Threading.Mutex & Semaphore
1.在VB6裡我們可以使用App.PrevInstance判斷程式是否已經在執行,若已在執行就關閉。
Private Sub Form_Initialize()
'攔截程式多開
If App.PrevInstance Then End
End Sub
2.在.Net可以用 GetProcessesByName方法 取得目前執行程式的名稱,Process.GetCurrentProcess().ProcessName。
GetProcessesByName方法 回傳陣列,所以若有大於1就表示有兩個程式在執行。
public bool PrevInstance()
{
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
return true;
}
else
{
return false;
}
}
3.也可以使用 System.Threading.Mutex 互斥,禁止程式同時執行
private bool IsMyMutex()
{
bool IsExist;
Mutex MyMutex = new Mutex(true, "OnlyRun", out IsExist);
if (IsExist)
{
return false;
}
else
{
return true;
}
}
範例下載:
2011-01-31補充
Semaphore類別也擁有具名鎖定的功能,同樣的也能利用它來達到目的。
private bool IsNotSemaphore()
{
bool IsExist;
Semaphore s = new Semaphore(1, 1, "OnlyRun", out IsExist);
if (IsExist)
return false;
else
return true;
}
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET