From 7ea279a32992565e2b08f459f9f02e6d41ed271b Mon Sep 17 00:00:00 2001 From: Ivan Martell Date: Thu, 29 Aug 2024 21:17:21 +0900 Subject: [PATCH] Cleanup --- LittleWarGameClient/Handlers/AudioHandler.cs | 27 +++---- .../Handlers/SettingsHandler.cs | 7 +- LittleWarGameClient/OverlayForm.cs | 18 ++--- LittleWarGameClient/Program.cs | 72 +++++++++---------- 4 files changed, 57 insertions(+), 67 deletions(-) diff --git a/LittleWarGameClient/Handlers/AudioHandler.cs b/LittleWarGameClient/Handlers/AudioHandler.cs index ac81d21..777fc84 100644 --- a/LittleWarGameClient/Handlers/AudioHandler.cs +++ b/LittleWarGameClient/Handlers/AudioHandler.cs @@ -7,7 +7,7 @@ namespace LittleWarGameClient.Handlers { internal class AudioHandler : IAudioSessionEventsHandler { - private MMDevice? mainDevice; + private readonly MMDevice? mainDevice; private AudioSessionControl? currentSession; private readonly string formTitle; @@ -89,7 +89,7 @@ private void ChangeTextAndIcon(AudioSessionControl session) private void AudioSessionManager_OnSessionCreated(object sender, IAudioSessionControl newSession) { - AudioSessionControl managedControl = new AudioSessionControl(newSession); + AudioSessionControl managedControl = new(newSession); ChangeTextAndIcon(managedControl); } @@ -97,26 +97,21 @@ private void AudioSessionManager_OnSessionCreated(object sender, IAudioSessionCo { try { - using (var query = new ManagementObjectSearcher( + using var query = new ManagementObjectSearcher( "SELECT * " + "FROM Win32_Process " + - "WHERE ProcessId=" + process.Id)) + "WHERE ProcessId=" + process.Id); + using var processes = query.Get(); + var filteredProcesses = processes.OfType().FirstOrDefault(); + if (filteredProcesses != null) { - using (var collection = query.Get()) + using (filteredProcesses) { - var mo = collection.OfType().FirstOrDefault(); - if (mo != null) - { - using (mo) - { - var p = Process.GetProcessById((int)(uint)mo["ParentProcessId"]); - return p; - } - } - + var p = Process.GetProcessById((int)(uint)filteredProcesses["ParentProcessId"]); + return p; } - return null; } + return null; } catch { diff --git a/LittleWarGameClient/Handlers/SettingsHandler.cs b/LittleWarGameClient/Handlers/SettingsHandler.cs index 3d650d8..96d7aa2 100644 --- a/LittleWarGameClient/Handlers/SettingsHandler.cs +++ b/LittleWarGameClient/Handlers/SettingsHandler.cs @@ -92,10 +92,8 @@ internal async Task SaveAsync() { try { - using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) - { - await settings.SaveToAsync(stream); - } + using FileStream stream = new(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true); + await settings.SaveToAsync(stream); } catch { @@ -212,6 +210,7 @@ public double GetVolume() } } + [AttributeUsage(AttributeTargets.Method)] internal class Hotkey : Attribute { public string? FuncToCall { get; set; } diff --git a/LittleWarGameClient/OverlayForm.cs b/LittleWarGameClient/OverlayForm.cs index 38fd8b8..f9f34cb 100644 --- a/LittleWarGameClient/OverlayForm.cs +++ b/LittleWarGameClient/OverlayForm.cs @@ -6,15 +6,15 @@ namespace LittleWarGameClient { - internal struct Notification + internal readonly record struct Notification { - internal string message { get; } - internal DateTime postedTime { get; } + internal string Message { get; } + internal DateTime PostedTime { get; } internal Notification(string msg) { - this.message = msg; - this.postedTime = DateTime.Now; + Message = msg; + PostedTime = DateTime.Now; } } @@ -32,10 +32,10 @@ internal static OverlayForm Instance } private bool IsGameFormLoaded = false; - private BDictionary overlayMessages; + private readonly BDictionary overlayMessages; internal void AddOverlayMessage(string name, Notification notification) { - overlayMessages[name] = new Notification(notification.message); + overlayMessages[name] = new Notification(notification.Message); } internal bool IsActivated { get; private set; } @@ -64,7 +64,7 @@ protected override void OnRender(D2DGraphics g) var overlayMessageValue = overlayMessages.TryGet(i); if (overlayMessageValue.HasValue) { - var notification = overlayMessageValue.Value.Value.message; + var notification = overlayMessageValue.Value.Value.Message; g.DrawText($" >{notification}", D2DColor.Yellow, Font, 0, (i + 1) * 30); } } @@ -74,7 +74,7 @@ private void textTimer_Tick(object sender, EventArgs e) { for (int i = 0; i < overlayMessages.Count; i++) { - if (overlayMessages[i].Value.postedTime.AddSeconds(6) < DateTime.Now) + if (overlayMessages[i].Value.PostedTime.AddSeconds(6) < DateTime.Now) overlayMessages.RemoveAt(i); } } diff --git a/LittleWarGameClient/Program.cs b/LittleWarGameClient/Program.cs index b21656f..767e780 100644 --- a/LittleWarGameClient/Program.cs +++ b/LittleWarGameClient/Program.cs @@ -7,19 +7,18 @@ namespace LittleWarGameClient internal static class Program { [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetForegroundWindow(IntPtr hWnd); - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); + private static extern void SetForegroundWindow(IntPtr hWnd); - [DllImport("User32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool EnumWindows(CallBackPtr lpEnumFunc, IntPtr lParam); + [DllImport("user32.dll")] + private static extern void GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); + + [DllImport("user32.dll")] + private static extern void EnumWindows(CallBackPtr lpEnumFunc, IntPtr lParam); private delegate bool CallBackPtr(IntPtr hwnd, int lParam); - private static CallBackPtr callBackPtr = Callback; - private static List _WinStructList = new List(); + private static readonly CallBackPtr callBackPtr = Callback; + private static List _WinStructList = new(); internal static bool IsDoubleInstance = false; @@ -30,42 +29,38 @@ internal static class Program static void Main() { var args = ParseArguments(Environment.GetCommandLineArgs()[1..]); - Thread splashthread = new Thread(() => + Thread splashthread = new(() => { SplashScreen.Instance.ShowDialog(); }); splashthread.IsBackground = true; splashthread.SetApartmentState(ApartmentState.STA); splashthread.Start(); - bool createdNew = true; - string? profileName; - if (!args.TryGetValue("profile", out profileName)) + if (!args.TryGetValue("profile", out string? profileName)) profileName = "main"; - using (Mutex mutex = new Mutex(true, $"Global\\LittleWarGameClient_{profileName}", out createdNew)) + using Mutex mutex = new(true, $"Global\\LittleWarGameClient_{profileName}", out bool createdNew); + if (createdNew) { - if (createdNew) - { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - GameForm.InstanceName = profileName; - ApplicationConfiguration.Initialize(); - Application.Run(OverlayForm.Instance); - } - else + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + GameForm.InstanceName = profileName; + ApplicationConfiguration.Initialize(); + Application.Run(OverlayForm.Instance); + } + else + { + IsDoubleInstance = true; + Process current = Process.GetCurrentProcess(); + foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { - IsDoubleInstance = true; - Process current = Process.GetCurrentProcess(); - foreach (Process process in Process.GetProcessesByName(current.ProcessName)) + if (process.Id != current.Id) { - if (process.Id != current.Id) + var clientWindows = GetWindows(process.Handle).Where(window => window.WinTitle == $"Littlewargame({profileName})"); + if (clientWindows.Any()) { - var clientWindows = GetWindows(process.Handle).Where(window => window.WinTitle == $"Littlewargame({profileName})"); - if (clientWindows.Count() > 0) - { - var clientMainWindow = clientWindows.First(); - SetForegroundWindow(clientMainWindow.MainWindowHandle); - break; - } + var clientMainWindow = clientWindows.First(); + SetForegroundWindow(clientMainWindow.MainWindowHandle); + break; } } } @@ -75,7 +70,7 @@ static void Main() private static Dictionary ParseArguments(string[] args) { args = Array.ConvertAll(args, d => d.ToLower()); - Dictionary arguments = new Dictionary(); + Dictionary arguments = new(); for (int i = 0; i < args.Length; i += 2) { @@ -92,9 +87,10 @@ private static Dictionary ParseArguments(string[] args) private static bool Callback(IntPtr hWnd, int lparam) { - StringBuilder sb = new StringBuilder(256); - int res = GetWindowText(hWnd, sb, 256); - _WinStructList.Add(new WinStruct { MainWindowHandle = hWnd, WinTitle = sb.ToString() }); + StringBuilder sb = new(256); + GetWindowText(hWnd, sb, 256); + if (sb.Length > 0) + _WinStructList.Add(new WinStruct { MainWindowHandle = hWnd, WinTitle = sb.ToString() }); return true; }