SystemTrayMenu/Utilities/SingleAppInstance.cs

66 lines
2.1 KiB
C#
Raw Normal View History

2020-03-17 09:05:52 +13:00
using System;
using System.ComponentModel;
2020-03-17 02:45:19 +13:00
using System.Diagnostics;
using System.Linq;
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))
{
if (!p.CloseMainWindow())
{
p.Kill();
}
2020-03-17 02:45:19 +13:00
p.WaitForExit();
p.Close();
2020-03-17 02:45:19 +13:00
killedAProcess = true;
}
}
2020-03-17 09:05:52 +13:00
catch (Exception ex)
2020-03-17 02:45:19 +13:00
{
if (ex is Win32Exception ||
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;
}
}
}
}