From bf6b71fb76a4ff5bbb9051e0e1104f7d9bbe6cd3 Mon Sep 17 00:00:00 2001 From: Matthew Roselli Date: Thu, 3 Dec 2015 20:55:41 -0600 Subject: [PATCH] Fix closing Honorbuddy gracefully. Honorbuddy changed it's main window. See https://github.com/aash/HBRelog/issues/29 --- Honorbuddy/HonorbuddyManager.cs | 2 +- NativeMethods.cs | 1 + Utility.cs | 23 +++++++++++++++++++++-- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/Honorbuddy/HonorbuddyManager.cs b/Honorbuddy/HonorbuddyManager.cs index 019ad88..dffc6c8 100644 --- a/Honorbuddy/HonorbuddyManager.cs +++ b/Honorbuddy/HonorbuddyManager.cs @@ -101,7 +101,7 @@ public void CloseBotProcess() if (!_isExiting && BotProcess != null && !BotProcess.HasExitedSafe()) { _isExiting = true; - Task.Run(async () => await Utility.CloseBotProcessAsync(BotProcess, Profile)) + Task.Run(async () => await Utility.CloseBotProcessAsync(BotProcess, Profile, "Honorbuddy")) .ContinueWith(o => { _isExiting = false; diff --git a/NativeMethods.cs b/NativeMethods.cs index 0d6314e..19cb7a7 100644 --- a/NativeMethods.cs +++ b/NativeMethods.cs @@ -1178,6 +1178,7 @@ public enum SystemMetric : int public enum Message : uint { + CLOSE = (0x0010), NCHITTEST = (0x0084), KEY_DOWN = (0x0100), //Key down KEY_UP = (0x0101), //Key Up diff --git a/Utility.cs b/Utility.cs index 7b2b70a..bae0d9d 100644 --- a/Utility.cs +++ b/Utility.cs @@ -419,12 +419,31 @@ public static void RestoreForegroundWindowAndMouse() #endregion - public static async Task CloseBotProcessAsync(Process proc, CharacterProfile profile) + public static async Task CloseBotProcessAsync(Process proc, CharacterProfile profile, String windowText = "") { var procName = proc.ProcessName; profile.Log("Attempting to close {0}", procName); - proc.CloseMainWindow(); + // If a specific window name was given, close that window instead of main window. + // StartsWith() is used instead of Equals() because Honorbuddy appends " - attached to ..." in title + if( !String.IsNullOrEmpty(windowText)) + { + IntPtr wHnd = NativeMethods.EnumerateProcessWindowHandles(proc.Id) + .FirstOrDefault((p => NativeMethods.GetWindowText(p).StartsWith(windowText))); + if( wHnd != IntPtr.Zero ) + { + NativeMethods.PostMessage(wHnd, (uint)NativeMethods.Message.CLOSE, IntPtr.Zero, UIntPtr.Zero); + } + else + { + proc.CloseMainWindow(); + } + } + else + { + proc.CloseMainWindow(); + } + if (await WaitForProcessToExitAsync(proc, TimeSpan.FromSeconds(10))) { profile.Log("Successfully closed {0} gracefully", procName);