2020-03-17 09:05:52 +13:00
|
|
|
|
using System;
|
2020-03-30 06:26:45 +13:00
|
|
|
|
using System.ComponentModel;
|
2020-03-17 02:45:19 +13:00
|
|
|
|
using System.Diagnostics;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
2020-03-28 12:42:32 +13:00
|
|
|
|
namespace SystemTrayMenu.Utilities
|
2020-03-17 02:45:19 +13:00
|
|
|
|
{
|
|
|
|
|
internal static class SingleAppInstance
|
|
|
|
|
{
|
|
|
|
|
internal static void Initialize()
|
|
|
|
|
{
|
|
|
|
|
if (IsAnyOtherInstancesofAppAlreadyRunning())
|
|
|
|
|
{
|
|
|
|
|
KillOtherInstancesOfApp();
|
|
|
|
|
bool KillOtherInstancesOfApp()
|
|
|
|
|
{
|
|
|
|
|
bool killedAProcess = false;
|
|
|
|
|
int ownPID = Process.GetCurrentProcess().Id;
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
foreach (Process p in Process.GetProcessesByName(
|
|
|
|
|
Process.GetCurrentProcess().ProcessName).
|
|
|
|
|
Where(p => p.Id != ownPID))
|
|
|
|
|
{
|
|
|
|
|
p.Kill();
|
|
|
|
|
p.WaitForExit();
|
|
|
|
|
killedAProcess = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-03-17 09:05:52 +13:00
|
|
|
|
catch (Exception ex)
|
2020-03-17 02:45:19 +13:00
|
|
|
|
{
|
2020-03-30 06:59:43 +13:00
|
|
|
|
if (ex is Win32Exception ||
|
2020-03-30 06:26:45 +13:00
|
|
|
|
ex is SystemException)
|
|
|
|
|
{
|
|
|
|
|
Log.Error("Run as single instance failed", ex);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
throw;
|
|
|
|
|
}
|
2020-03-17 02:45:19 +13:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return killedAProcess;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
bool IsAnyOtherInstancesofAppAlreadyRunning()
|
|
|
|
|
{
|
|
|
|
|
//string pid = Process.Id.ToString();
|
|
|
|
|
foreach (Process p in Process.GetProcessesByName(
|
|
|
|
|
Process.GetCurrentProcess().ProcessName).
|
|
|
|
|
Where(s => s.Id != Process.GetCurrentProcess().Id))
|
|
|
|
|
{
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|