SystemTrayMenu/Utilities/SingleAppInstance.cs

71 lines
2.2 KiB
C#
Raw Normal View History

// <copyright file="SingleAppInstance.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
2020-03-17 02:45:19 +13:00
namespace SystemTrayMenu.Utilities
2020-03-17 02:45:19 +13:00
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
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;
}
}
static bool IsAnyOtherInstancesofAppAlreadyRunning()
2020-03-17 02:45:19 +13:00
{
foreach (Process p in Process.GetProcessesByName(
Process.GetCurrentProcess().ProcessName).
Where(s => s.Id != Process.GetCurrentProcess().Id))
{
return true;
}
return false;
}
}
}
}