System.Threading.Mutex mutex;//注意,此變量要定義為成員變量,而不是局部變量
bool CheckMultiInstance()
{
bool createdNew = true;
mutex = new System.Threading.Mutex(true, "_TEST_Mutex_", out createdNew);//這種在系統多用戶下,每個用戶能啟動一個程序進程。
mutex = new System.Threading.Mutex(true, "Global\\_TEST_Mutex_", out createdNew);//這種在系統中,不管幾個用戶,只能存在一個這樣的程序進程
if (!createdNew)
{
MessageBox.Show("Program is already running.");
}
return createdNew;
}
/// <summary>
/// Is exist same process
/// </summary>
/// <returns></returns>
public static Process GetExistProcess()
{
try
{
var current = Process.GetCurrentProcess();
var pArrayy = System.Diagnostics.Process.GetProcessesByName(current.ProcessName);
if (pArrayy == null || pArrayy.Length == 0)
{
return null;
}
foreach (var item in pArrayy)
{
try
{
if (!item.ProcessName.ToUpper().Contains(current.ProcessNameToUpper()))
{
continue;
}
if (item.Id != current.Id && item.MainModule.ModuleName.ToUpper() == current.MainModule.ModuleName.ToUpper())
{
return item;
}
}
catch (Exception er)
{
LogHelper.WriteException(er);
continue;
}
}
}
catch (Exception ex)
{
LogHelper.WriteException(ex);
}
return null;
}