SystemTrayMenu/Utilities/SingleAppInstance.cs

97 lines
3.6 KiB
C#
Raw Permalink 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using SystemTrayMenu.UserInterface.HotkeyTextboxControl;
using WindowsInput;
2020-03-17 02:45:19 +13:00
internal static class SingleAppInstance
{
internal static bool Initialize()
2020-03-17 02:45:19 +13:00
{
bool success = true;
try
2020-03-17 02:45:19 +13:00
{
foreach (Process p in Process.GetProcessesByName(
Process.GetCurrentProcess().ProcessName).
Where(s => s.Id != Environment.ProcessId))
2020-03-17 02:45:19 +13:00
{
if (Properties.Settings.Default.SendHotkeyInsteadKillOtherInstances)
{
Keys modifiers = HotkeyControl.HotkeyModifiersFromString(Properties.Settings.Default.HotKey);
Keys hotkey = HotkeyControl.HotkeyFromString(Properties.Settings.Default.HotKey);
try
{
List<VirtualKeyCode> virtualKeyCodesModifiers = new();
foreach (string key in modifiers.ToString().ToUpperInvariant().Split(", "))
{
if (key == "NONE")
{
continue;
}
VirtualKeyCode virtualKeyCode = VirtualKeyCode.LWIN;
virtualKeyCode = key switch
{
"ALT" => VirtualKeyCode.MENU,
_ => (VirtualKeyCode)Enum.Parse(
typeof(VirtualKeyCode), key.ToUpperInvariant()),
};
virtualKeyCodesModifiers.Add(virtualKeyCode);
}
VirtualKeyCode virtualKeyCodeHotkey = 0;
if (Enum.IsDefined(typeof(VirtualKeyCode), (int)hotkey))
{
virtualKeyCodeHotkey = (VirtualKeyCode)(int)hotkey;
}
new InputSimulator().Keyboard.ModifiedKeyStroke(virtualKeyCodesModifiers, virtualKeyCodeHotkey);
success = false;
}
catch (Exception ex)
{
Log.Warn($"Send hoktey {Properties.Settings.Default.HotKey} to other instance failed", ex);
}
}
2020-03-17 02:45:19 +13:00
if (!Properties.Settings.Default.SendHotkeyInsteadKillOtherInstances)
2020-03-17 02:45:19 +13:00
{
try
2020-03-17 02:45:19 +13:00
{
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
}
catch (Exception ex)
{
Log.Error("Run as single instance failed", ex);
success = false;
}
2020-03-17 02:45:19 +13:00
}
}
}
catch (Exception ex)
2020-03-17 02:45:19 +13:00
{
Log.Error("Run as single instance failed", ex);
2020-03-17 02:45:19 +13:00
}
return success;
2020-03-17 02:45:19 +13:00
}
}
}