GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
refactor: global exception handling (#130)
lars-bergerb9dd41cf0653
diff --git a/GlazeWM.Bar/BarService.cs b/GlazeWM.Bar/BarService.csindex 13c6cc27..4f30e499 100644--- a/GlazeWM.Bar/BarService.cs+++ b/GlazeWM.Bar/BarService.cs@@ -2,6 +2,7 @@ using GlazeWM.Domain.Monitors;using GlazeWM.Domain.Monitors.Events;using GlazeWM.Domain.UserConfigs.Events;using GlazeWM.Infrastructure.Bussing;+using GlazeWM.Infrastructure.Exceptions;using System.Reactive.Linq;using System;using System.Threading;@@ -16,35 +17,44 @@ namespace GlazeWM.Bar{private readonly Bus _bus;private readonly MonitorService _monitorService;+ private readonly ExceptionHandler _exceptionHandler;private Application _application;private readonly Dictionary<string, MainWindow> _activeWindowsByDeviceName = new();- public BarService(Bus bus, MonitorService monitorService)+ public BarService(Bus bus, MonitorService monitorService, ExceptionHandler exceptionHandler){_bus = bus;_monitorService = monitorService;+ _exceptionHandler = exceptionHandler;}public void StartApp(){var thread = new Thread(() =>{- _application = new()+ try{- ShutdownMode = ShutdownMode.OnExplicitShutdown- };+ _application = new()+ {+ ShutdownMode = ShutdownMode.OnExplicitShutdown+ };- // Launch the bar window on the added monitor.- _bus.Events.OfType<MonitorAddedEvent>()- .Subscribe((@event) => ShowWindow(@event.AddedMonitor));+ // Launch the bar window on the added monitor.+ _bus.Events.OfType<MonitorAddedEvent>()+ .Subscribe((@event) => ShowWindow(@event.AddedMonitor));- _bus.Events.OfType<MonitorRemovedEvent>()- .Subscribe((@event) => CloseWindow(@event.RemovedDeviceName));+ _bus.Events.OfType<MonitorRemovedEvent>()+ .Subscribe((@event) => CloseWindow(@event.RemovedDeviceName));- _bus.Events.OfType<UserConfigReloadedEvent>()- .Subscribe((_) => RestartApp());+ _bus.Events.OfType<UserConfigReloadedEvent>()+ .Subscribe((_) => RestartApp());- _application.Run();+ _application.Run();+ }+ catch (Exception exception)+ {+ _exceptionHandler.HandleFatalException(exception);+ }}){Name = "GlazeWMBar"diff --git a/GlazeWM.Bootstrapper/Program.cs b/GlazeWM.Bootstrapper/Program.csindex 9d90e2d5..fbaaa64e 100644--- a/GlazeWM.Bootstrapper/Program.cs+++ b/GlazeWM.Bootstrapper/Program.cs@@ -1,7 +1,10 @@using GlazeWM.Bar;using GlazeWM.Domain;+using GlazeWM.Domain.Containers;using GlazeWM.Infrastructure;+using GlazeWM.Infrastructure.Exceptions;using GlazeWM.Infrastructure.Logging;+using GlazeWM.Infrastructure.Serialization;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;@@ -9,6 +12,8 @@ using Microsoft.Extensions.Logging.Console;using System;using System.Collections.Generic;using System.Diagnostics;+using System.IO;+using System.Text.Json.Serialization;using System.Threading;using Microsoft.Extensions.Configuration;@@ -60,6 +65,29 @@ namespace GlazeWM.Bootstrapperservices.AddDomainServices();services.AddBarServices();services.AddSingleton<Startup>();++ // Configure exception handler.+ services+ .AddOptions<ExceptionHandlerOptions>()+ .Configure<ContainerService, JsonService>((options, containerService, jsonService) =>+ {+ options.ErrorLogPath = Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),+ "./.glaze-wm/errors.log"+ );++ options.ErrorLogMessageDelegate = (Exception exception) =>+ {+ var stateDump = jsonService.Serialize(+ containerService.ContainerTree,+ new List<JsonConverter> { new JsonContainerConverter() }+ );++ return $"{DateTime.Now}\n"+ + $"{exception}\n"+ + $"State dump: {stateDump}\n\n";+ };+ });}).ConfigureLogging(builder =>{diff --git a/GlazeWM.Bootstrapper/Startup.cs b/GlazeWM.Bootstrapper/Startup.csindex 68bb6751..56030775 100644--- a/GlazeWM.Bootstrapper/Startup.cs+++ b/GlazeWM.Bootstrapper/Startup.cs@@ -1,17 +1,13 @@using GlazeWM.Bar;using GlazeWM.Domain.Common.Commands;-using GlazeWM.Domain.Containers;using GlazeWM.Domain.Windows.Commands;using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.Serialization;+using GlazeWM.Infrastructure.Exceptions;using GlazeWM.Infrastructure.WindowsApi;using GlazeWM.Infrastructure.WindowsApi.Events;using System;-using System.Collections.Generic;-using System.IO;using System.Linq;using System.Reactive.Linq;-using System.Text.Json.Serialization;using System.Windows.Forms;using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;@@ -19,64 +15,67 @@ namespace GlazeWM.Bootstrapper{internal class Startup{+ private readonly BarService _barService;private readonly Bus _bus;- private readonly ContainerService _containerService;- private readonly JsonService _jsonService;+ private readonly ExceptionHandler _exceptionHandler;private readonly KeybindingService _keybindingService;- private readonly WindowEventService _windowEventService;- private readonly BarService _barService;- private readonly SystemTrayService _systemTrayService;private readonly SystemEventService _systemEventService;+ private readonly SystemTrayService _systemTrayService;+ private readonly WindowEventService _windowEventService;public Startup(+ BarService barService,Bus bus,- ContainerService containerService,- JsonService jsonService,+ ExceptionHandler exceptionHandler,KeybindingService keybindingService,- WindowEventService windowEventService,- BarService barService,+ SystemEventService systemEventService,SystemTrayService systemTrayService,- SystemEventService systemEventService)+ WindowEventService windowEventService){+ _barService = barService;_bus = bus;- _containerService = containerService;- _jsonService = jsonService;+ _exceptionHandler = exceptionHandler;_keybindingService = keybindingService;- _windowEventService = windowEventService;- _barService = barService;- _systemTrayService = systemTrayService;_systemEventService = systemEventService;+ _systemTrayService = systemTrayService;+ _windowEventService = windowEventService;}public void Run(){- // Set the process-default DPI awareness.- _ = SetProcessDpiAwarenessContext(DpiAwarenessContext.Context_PerMonitorAwareV2);+ try+ {+ // Set the process-default DPI awareness.+ _ = SetProcessDpiAwarenessContext(DpiAwarenessContext.Context_PerMonitorAwareV2);- _bus.FatalException.Subscribe(_ => WriteStateDumpToErrorLog());- _bus.Events.OfType<ApplicationExitingEvent>()- .Subscribe(_ => OnApplicationExit());+ _bus.Events.OfType<ApplicationExitingEvent>()+ .Subscribe(_ => OnApplicationExit());- // Launch bar WPF application. Spawns bar window when monitors are added, so the service needs- // to be initialized before populating initial state.- _barService.StartApp();+ // Launch bar WPF application. Spawns bar window when monitors are added, so the service needs+ // to be initialized before populating initial state.+ _barService.StartApp();- // Populate initial monitors, windows, workspaces and user config.- _bus.Invoke(new PopulateInitialStateCommand());+ // Populate initial monitors, windows, workspaces and user config.+ _bus.Invoke(new PopulateInitialStateCommand());- // Listen on registered keybindings.- _keybindingService.Start();+ // Listen on registered keybindings.+ _keybindingService.Start();- // Listen for window events (eg. close, focus).- _windowEventService.Start();+ // Listen for window events (eg. close, focus).+ _windowEventService.Start();- // Listen for system-related events (eg. changes to display settings).- _systemEventService.Start();+ // Listen for system-related events (eg. changes to display settings).+ _systemEventService.Start();- // Add application to system tray.- _systemTrayService.AddToSystemTray();+ // Add application to system tray.+ _systemTrayService.AddToSystemTray();- Application.Run();+ Application.Run();+ }+ catch (Exception exception)+ {+ _exceptionHandler.HandleFatalException(exception);+ }}private void OnApplicationExit()@@ -85,29 +84,6 @@ namespace GlazeWM.Bootstrapper_barService.ExitApp();_systemTrayService.RemoveFromSystemTray();Application.Exit();- // TODO: Use exit code 1 if exiting due to an unhandled error.- Environment.Exit(0);- }-- // TODO: Move to dedicated logging service.- private void WriteStateDumpToErrorLog()- {- var errorLogPath = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),- "./.glaze-wm/errors.log"- );-- Directory.CreateDirectory(Path.GetDirectoryName(errorLogPath));-- try- {- var stateDump = _jsonService.Serialize(_containerService.ContainerTree, new List<JsonConverter> { new JsonContainerConverter() });- File.AppendAllText(errorLogPath, $"\nState dump: {stateDump}");- }- catch (Exception)- {- File.AppendAllText(errorLogPath, "\nFailed to get state dump.");- }}}}diff --git a/GlazeWM.Domain/Common/CommandHandlers/ExecProcessHandler.cs b/GlazeWM.Domain/Common/CommandHandlers/ExecProcessHandler.csindex 65f839e8..0d5c80e1 100644--- a/GlazeWM.Domain/Common/CommandHandlers/ExecProcessHandler.cs+++ b/GlazeWM.Domain/Common/CommandHandlers/ExecProcessHandler.cs@@ -1,8 +1,8 @@using System;using System.Diagnostics;-using System.Windows.Forms;using GlazeWM.Domain.Common.Commands;using GlazeWM.Infrastructure.Bussing;+using GlazeWM.Infrastructure.Exceptions;namespace GlazeWM.Domain.Common.CommandHandlers{@@ -31,8 +31,7 @@ namespace GlazeWM.Domain.Common.CommandHandlerscatch (Exception exception){// TODO: Link to documentation for `exec` command (no proper documentation yet).- // TODO: Handle non-fatal exceptions in a generic way.- MessageBox.Show(exception.Message);+ ExceptionHandler.HandleNonFatalException(exception);}return CommandResponse.Ok;diff --git a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs b/GlazeWM.Domain/UserConfigs/CommandParsingService.csindex 18ee92fa..cb632351 100644--- a/GlazeWM.Domain/UserConfigs/CommandParsingService.cs+++ b/GlazeWM.Domain/UserConfigs/CommandParsingService.cs@@ -200,7 +200,7 @@ namespace GlazeWM.Domain.UserConfigs{return commandParts[1] switch{- "wm" => new ExitApplicationCommand(),+ "wm" => new ExitApplicationCommand(false),_ => throw new ArgumentException(null, nameof(commandParts)),};}diff --git a/GlazeWM.Infrastructure/Bussing/Bus.cs b/GlazeWM.Infrastructure/Bussing/Bus.csindex 94a5bc11..d44d9633 100644--- a/GlazeWM.Infrastructure/Bussing/Bus.cs+++ b/GlazeWM.Infrastructure/Bussing/Bus.cs@@ -1,13 +1,8 @@-using GlazeWM.Infrastructure.Exceptions;-using GlazeWM.Infrastructure.WindowsApi.Events;-using Microsoft.Extensions.DependencyInjection;+using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using System;using System.Collections.Generic;-using System.Diagnostics;-using System.IO;using System.Reactive.Subjects;-using System.Windows.Forms;namespace GlazeWM.Infrastructure.Bussing{@@ -17,8 +12,7 @@ namespace GlazeWM.Infrastructure.Bussingpublic sealed class Bus{public readonly Subject<Event> Events = new();- public readonly Subject<bool> FatalException = new();- private readonly object _lockObj = new();+ public readonly object LockObj = new();private readonly ILogger<Bus> _logger;public Bus(ILogger<Bus> logger)@@ -31,25 +25,17 @@ namespace GlazeWM.Infrastructure.Bussing/// </summary>public CommandResponse Invoke<T>(T command) where T : Command{- try- {- _logger.LogDebug("Command {commandName} invoked.", command.Name);+ _logger.LogDebug("Command {commandName} invoked.", command.Name);- // Create a `Type` object representing the constructed `ICommandHandler` generic.- var handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());+ // Create a `Type` object representing the constructed `ICommandHandler` generic.+ var handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());- var handlerInstance = ServiceLocator.Provider.GetRequiredService(handlerType)- as ICommandHandler<T>;+ var handlerInstance = ServiceLocator.Provider.GetRequiredService(handlerType)+ as ICommandHandler<T>;- lock (_lockObj)- {- return handlerInstance.Handle(command);- }- }- catch (Exception error)+ lock (LockObj){- HandleError(error);- throw;+ return handlerInstance.Handle(command);}}@@ -58,56 +44,22 @@ namespace GlazeWM.Infrastructure.Bussing/// </summary>public void RaiseEvent<T>(T @event) where T : Event{- try- {- // Create a `Type` object representing the constructed `IEventHandler` generic.- var handlerType = typeof(IEventHandler<>).MakeGenericType(@event.GetType());+ // Create a `Type` object representing the constructed `IEventHandler` generic.+ var handlerType = typeof(IEventHandler<>).MakeGenericType(@event.GetType());- var handlerInstances = ServiceLocator.Provider.GetServices(handlerType)- as IEnumerable<IEventHandler<T>>;+ var handlerInstances = ServiceLocator.Provider.GetServices(handlerType)+ as IEnumerable<IEventHandler<T>>;- foreach (var handler in handlerInstances)+ foreach (var handler in handlerInstances)+ {+ lock (LockObj){- lock (_lockObj)- {- handler.Handle(@event);- }+ handler.Handle(@event);}-- // Emit event through subject.- Events.OnNext(@event);- }- catch (Exception error)- {- HandleError(error);- throw;}- }-- private void HandleError(Exception error)- {- // Alert the user of the error.- if (error is FatalUserException)- MessageBox.Show(error.Message);-- WriteToErrorLog(error);- RaiseEvent(new ApplicationExitingEvent());- }-- // TODO: Move to dedicated logging service.- private void WriteToErrorLog(Exception error)- {- var errorLogPath = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),- "./.glaze-wm/errors.log"- );-- Directory.CreateDirectory(Path.GetDirectoryName(errorLogPath));- File.AppendAllText(errorLogPath, $"\n\n{DateTime.Now}\n{error.Message + error.ToString()}");- File.AppendAllText(errorLogPath, "\n-- END OF INNER EXCEPTION --");- File.AppendAllText(errorLogPath, $"\n{new StackTrace(3, true)}");- FatalException.OnNext(true);+ // Emit event through subject.+ Events.OnNext(@event);}}}diff --git a/GlazeWM.Infrastructure/Common/CommandHandlers/ExitApplicationHandler.cs b/GlazeWM.Infrastructure/Common/CommandHandlers/ExitApplicationHandler.csindex 1926fcf3..9f0288eb 100644--- a/GlazeWM.Infrastructure/Common/CommandHandlers/ExitApplicationHandler.cs+++ b/GlazeWM.Infrastructure/Common/CommandHandlers/ExitApplicationHandler.cs@@ -1,3 +1,4 @@+using System;using GlazeWM.Infrastructure.Bussing;using GlazeWM.Infrastructure.Common.Commands;using GlazeWM.Infrastructure.WindowsApi.Events;@@ -15,8 +16,14 @@ namespace GlazeWM.Infrastructure.Common.CommandHandlerspublic CommandResponse Handle(ExitApplicationCommand command){+ var withErrorCode = command.WithErrorCode;++ // Signal that application is about to exit (to perform cleanup)._bus.RaiseEvent(new ApplicationExitingEvent());+ // Use exit code 1 if exiting due to an exception.+ Environment.Exit(withErrorCode ? 1 : 0);+return CommandResponse.Ok;}}diff --git a/GlazeWM.Infrastructure/Common/Commands/ExitApplicationCommand.cs b/GlazeWM.Infrastructure/Common/Commands/ExitApplicationCommand.csindex 24503fd5..0cb158ab 100644--- a/GlazeWM.Infrastructure/Common/Commands/ExitApplicationCommand.cs+++ b/GlazeWM.Infrastructure/Common/Commands/ExitApplicationCommand.cs@@ -4,5 +4,11 @@ namespace GlazeWM.Infrastructure.Common.Commands{public class ExitApplicationCommand : Command{+ public bool WithErrorCode { get; }++ public ExitApplicationCommand(bool withErrorCode)+ {+ WithErrorCode = withErrorCode;+ }}}diff --git a/GlazeWM.Infrastructure/DependencyInjection.cs b/GlazeWM.Infrastructure/DependencyInjection.csindex b4a54513..ee39d97c 100644--- a/GlazeWM.Infrastructure/DependencyInjection.cs+++ b/GlazeWM.Infrastructure/DependencyInjection.cs@@ -1,6 +1,7 @@using GlazeWM.Infrastructure.Bussing;using GlazeWM.Infrastructure.Common.Commands;using GlazeWM.Infrastructure.Common.CommandHandlers;+using GlazeWM.Infrastructure.Exceptions;using GlazeWM.Infrastructure.Serialization;using GlazeWM.Infrastructure.WindowsApi;using Microsoft.Extensions.DependencyInjection;@@ -12,6 +13,7 @@ namespace GlazeWM.Infrastructurepublic static IServiceCollection AddInfrastructureServices(this IServiceCollection services){services.AddSingleton<Bus>();+ services.AddSingleton<ExceptionHandler>();services.AddSingleton<KeybindingService>();services.AddSingleton<SystemEventService>();services.AddSingleton<SystemTrayService>();diff --git a/GlazeWM.Infrastructure/Exceptions/ExceptionHandler.cs b/GlazeWM.Infrastructure/Exceptions/ExceptionHandler.csnew file mode 100644index 00000000..2c1fe3d9--- /dev/null+++ b/GlazeWM.Infrastructure/Exceptions/ExceptionHandler.cs@@ -0,0 +1,54 @@+using System;+using System.IO;+using System.Windows.Forms;+using GlazeWM.Infrastructure.Bussing;+using GlazeWM.Infrastructure.Common.Commands;+using Microsoft.Extensions.Options;++namespace GlazeWM.Infrastructure.Exceptions+{+ public class ExceptionHandler+ {+ private readonly Bus _bus;+ private readonly IOptions<ExceptionHandlerOptions> _options;++ public ExceptionHandler(Bus bus, IOptions<ExceptionHandlerOptions> options)+ {+ _bus = bus;+ _options = options;+ }++ public static void HandleNonFatalException(Exception exception)+ {+ // Alert the user of the error.+ MessageBox.Show(exception.Message);+ }++ public void HandleFatalException(Exception exception)+ {+ // Lock bus to prevent further state changes while showing message box and writing to logs.+ lock (_bus.LockObj)+ {+ // Alert the user of the error.+ MessageBox.Show($"Unhandled exception: {exception.Message}");++ WriteToErrorLog(exception);++ _bus.Invoke(new ExitApplicationCommand(true));+ }+ }++ private void WriteToErrorLog(Exception exception)+ {+ var errorLogPath = _options.Value.ErrorLogPath;++ // Create containing directory. Needs to be created before writing to the file.+ Directory.CreateDirectory(Path.GetDirectoryName(errorLogPath));++ File.AppendAllText(+ errorLogPath,+ _options.Value.ErrorLogMessageDelegate(exception)+ );+ }+ }+}diff --git a/GlazeWM.Infrastructure/Exceptions/ExceptionHandlerOptions.cs b/GlazeWM.Infrastructure/Exceptions/ExceptionHandlerOptions.csnew file mode 100644index 00000000..ed9239b9--- /dev/null+++ b/GlazeWM.Infrastructure/Exceptions/ExceptionHandlerOptions.cs@@ -0,0 +1,10 @@+using System;++namespace GlazeWM.Infrastructure.Exceptions+{+ public class ExceptionHandlerOptions+ {+ public string ErrorLogPath { get; set; }+ public Func<Exception, string> ErrorLogMessageDelegate { get; set; }+ }+}diff --git a/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs b/GlazeWM.Infrastructure/WindowsApi/KeybindingService.csindex f6fcdef4..962d4c2e 100644--- a/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs+++ b/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs@@ -3,7 +3,6 @@ using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Runtime.InteropServices;-using System.Threading;using System.Windows.Forms;using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;@@ -40,13 +39,20 @@ namespace GlazeWM.Infrastructure.WindowsApiKeys.RShiftKey};+ /// <summary>+ /// Store a reference to the hook delegate to prevent its garbage collection.+ /// </summary>+ private readonly HookProc _hookProc;++ public KeybindingService()+ {+ _hookProc = new HookProc(KeybindingHookProc);+ }+public void Start(){- var thread = new Thread(() => CreateKeybindingHook())- {- Name = "GlazeWMKeybindingService"- };- thread.Start();+ // Create low-level keyboard hook.+ _ = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, _hookProc, Process.GetCurrentProcess().MainModule.BaseAddress, 0);}public void AddGlobalKeybinding(string keybindingString, Action callback)@@ -82,14 +88,6 @@ namespace GlazeWM.Infrastructure.WindowsApireturn isNumeric ? $"D{key}" : key;}- private void CreateKeybindingHook()- {- _ = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, KeybindingHookProc, Process.GetCurrentProcess().MainModule.BaseAddress, 0);-- // `SetWindowsHookEx` requires a message loop within the thread that is executing the code.- Application.Run();- }-private IntPtr KeybindingHookProc(int nCode, IntPtr wParam, IntPtr lParam){var shouldPassThrough = nCode != 0 || !((uint)wParam == WM_KEYDOWN || (uint)wParam == WM_SYSKEYDOWN);diff --git a/GlazeWM.Infrastructure/WindowsApi/SystemTrayService.cs b/GlazeWM.Infrastructure/WindowsApi/SystemTrayService.csindex d8e429e4..b25ad4ba 100644--- a/GlazeWM.Infrastructure/WindowsApi/SystemTrayService.cs+++ b/GlazeWM.Infrastructure/WindowsApi/SystemTrayService.cs@@ -1,10 +1,9 @@using System;using System.Drawing;using System.Reflection;-using System.Threading;using System.Windows.Forms;using GlazeWM.Infrastructure.Bussing;-using GlazeWM.Infrastructure.WindowsApi.Events;+using GlazeWM.Infrastructure.Common.Commands;namespace GlazeWM.Infrastructure.WindowsApi{@@ -19,42 +18,28 @@ namespace GlazeWM.Infrastructure.WindowsApi}public void AddToSystemTray()- {- var thread = new Thread(() => PopulateSystemTray())- {- Name = "GlazeWMSystemTray"- };- thread.Start();- }-- private void PopulateSystemTray(){var contextMenuStrip = new ContextMenuStrip();-- contextMenuStrip.Items.Add("Exit", null, SignalApplicationExit);+ contextMenuStrip.Items.Add("Exit", null, ExitApplication);var assembly = Assembly.GetEntryAssembly();const string iconResourceName = "GlazeWM.Bootstrapper.icon.ico";// Get the embedded icon resource from the entry assembly.- using (var stream = assembly.GetManifestResourceStream(iconResourceName))- {- _notifyIcon = new NotifyIcon- {- Icon = new Icon(stream),- ContextMenuStrip = contextMenuStrip,- Text = "GlazeWM",- Visible = true- };- }+ using var stream = assembly.GetManifestResourceStream(iconResourceName);- // System tray requires a message loop within the thread that is executing the code.- Application.Run();+ _notifyIcon = new NotifyIcon+ {+ Icon = new Icon(stream),+ ContextMenuStrip = contextMenuStrip,+ Text = "GlazeWM",+ Visible = true+ };}- private void SignalApplicationExit(object sender, EventArgs e)+ private void ExitApplication(object sender, EventArgs e){- _bus.RaiseEvent(new ApplicationExitingEvent());+ _bus.Invoke(new ExitApplicationCommand(false));}public void RemoveFromSystemTray()diff --git a/GlazeWM.Infrastructure/WindowsApi/WindowEventService.cs b/GlazeWM.Infrastructure/WindowsApi/WindowEventService.csindex d70e38cd..c879fc98 100644--- a/GlazeWM.Infrastructure/WindowsApi/WindowEventService.cs+++ b/GlazeWM.Infrastructure/WindowsApi/WindowEventService.cs@@ -2,8 +2,6 @@using GlazeWM.Infrastructure.WindowsApi.Enums;using GlazeWM.Infrastructure.WindowsApi.Events;using System;-using System.Threading;-using System.Windows.Forms;using static GlazeWM.Infrastructure.WindowsApi.WindowsApiService;namespace GlazeWM.Infrastructure.WindowsApi@@ -11,32 +9,26 @@ namespace GlazeWM.Infrastructure.WindowsApipublic class WindowEventService{private readonly Bus _bus;++ /// <summary>+ /// Store a reference to the hook delegate to prevent its garbage collection.+ /// </summary>+ private readonly WindowEventProc _hookProc;private const int CHILDID_SELF = 0;public WindowEventService(Bus bus){_bus = bus;+ _hookProc = new WindowEventProc(WindowEventHookProc);}public void Start(){- var thread = new Thread(() => CreateWindowEventHook())- {- Name = "GlazeWMWindowHooks"- };- thread.Start();- }-- private void CreateWindowEventHook()- {- SetWinEventHook(EventConstant.EVENT_OBJECT_LOCATIONCHANGE, EventConstant.EVENT_OBJECT_LOCATIONCHANGE, IntPtr.Zero, WindowEventHookProc, 0, 0, 0);- SetWinEventHook(EventConstant.EVENT_OBJECT_DESTROY, EventConstant.EVENT_OBJECT_HIDE, IntPtr.Zero, WindowEventHookProc, 0, 0, 0);- SetWinEventHook(EventConstant.EVENT_SYSTEM_MINIMIZESTART, EventConstant.EVENT_SYSTEM_MINIMIZEEND, IntPtr.Zero, WindowEventHookProc, 0, 0, 0);- SetWinEventHook(EventConstant.EVENT_SYSTEM_MOVESIZEEND, EventConstant.EVENT_SYSTEM_MOVESIZEEND, IntPtr.Zero, WindowEventHookProc, 0, 0, 0);- SetWinEventHook(EventConstant.EVENT_SYSTEM_FOREGROUND, EventConstant.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, WindowEventHookProc, 0, 0, 0);-- // `SetWinEventHook` requires a message loop within the thread that is executing the code.- Application.Run();+ SetWinEventHook(EventConstant.EVENT_OBJECT_LOCATIONCHANGE, EventConstant.EVENT_OBJECT_LOCATIONCHANGE, IntPtr.Zero, _hookProc, 0, 0, 0);+ SetWinEventHook(EventConstant.EVENT_OBJECT_DESTROY, EventConstant.EVENT_OBJECT_HIDE, IntPtr.Zero, _hookProc, 0, 0, 0);+ SetWinEventHook(EventConstant.EVENT_SYSTEM_MINIMIZESTART, EventConstant.EVENT_SYSTEM_MINIMIZEEND, IntPtr.Zero, _hookProc, 0, 0, 0);+ SetWinEventHook(EventConstant.EVENT_SYSTEM_MOVESIZEEND, EventConstant.EVENT_SYSTEM_MOVESIZEEND, IntPtr.Zero, _hookProc, 0, 0, 0);+ SetWinEventHook(EventConstant.EVENT_SYSTEM_FOREGROUND, EventConstant.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _hookProc, 0, 0, 0);}private void WindowEventHookProc(IntPtr hWinEventHook, EventConstant eventType, IntPtr hwnd, ObjectIdentifier idObject, int idChild, uint dwEventThread, uint dwmsEventTime)