2020-07-07 07:15:45 +12:00
|
|
|
|
// <copyright file="SingleAppInstance.cs" company="PlaceholderCompany">
|
|
|
|
|
// Copyright (c) PlaceholderCompany. All rights reserved.
|
|
|
|
|
// </copyright>
|
2020-03-17 02:45:19 +13:00
|
|
|
|
|
2020-03-28 12:42:32 +13:00
|
|
|
|
namespace SystemTrayMenu.Utilities
|
2020-03-17 02:45:19 +13:00
|
|
|
|
{
|
2020-07-07 07:15:45 +12:00
|
|
|
|
using System;
|
|
|
|
|
using System.ComponentModel;
|
|
|
|
|
using System.Diagnostics;
|
|
|
|
|
using System.Linq;
|
2020-07-07 09:37:55 +12:00
|
|
|
|
|
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))
|
|
|
|
|
{
|
2020-06-29 19:16:23 +12:00
|
|
|
|
if (!p.CloseMainWindow())
|
|
|
|
|
{
|
|
|
|
|
p.Kill();
|
|
|
|
|
}
|
2020-07-07 07:15:45 +12:00
|
|
|
|
|
2020-03-17 02:45:19 +13:00
|
|
|
|
p.WaitForExit();
|
2020-06-29 19:16:23 +12:00
|
|
|
|
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
|
|
|
|
{
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-07-07 07:15:45 +12:00
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|