diff --git a/Notepad.Extensions.Logging/NativeMethods.cs b/Notepad.Extensions.Logging/NativeMethods.cs index 6de089f..9426460 100644 --- a/Notepad.Extensions.Logging/NativeMethods.cs +++ b/Notepad.Extensions.Logging/NativeMethods.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.InteropServices; +using System.Text; namespace Microsoft.Extensions.Logging { @@ -15,5 +16,13 @@ namespace Microsoft.Extensions.Logging [DllImport("User32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); + + public delegate bool EnumWindowsDelegate(IntPtr hWnd, IntPtr lParam); + + [DllImport("user32.dll")] + public static extern bool EnumWindows(EnumWindowsDelegate lpEnumFunc, IntPtr lParam); + + [DllImport("User32.dll")] + public static extern int GetWindowText(IntPtr hWndParent, StringBuilder sb, int maxCount); } } diff --git a/Notepad.Extensions.Logging/WindowFinder.cs b/Notepad.Extensions.Logging/WindowFinder.cs index a033593..19faae1 100644 --- a/Notepad.Extensions.Logging/WindowFinder.cs +++ b/Notepad.Extensions.Logging/WindowFinder.cs @@ -1,4 +1,6 @@ using System; +using System.ComponentModel; +using System.Text; namespace Microsoft.Extensions.Logging { @@ -6,28 +8,66 @@ namespace Microsoft.Extensions.Logging { public static IntPtr FindNotepadWindow() { - var hwnd = FindMainWindow(); - IntPtr edit = NativeMethods.FindWindowEx(hwnd, IntPtr.Zero, "EDIT", null); - return edit; + sb ??= new StringBuilder(4096); + + try + { + FindMainWindow(); + if (handle == IntPtr.Zero) + { + return handle; + } + + IntPtr edit = NativeMethods.FindWindowEx(handle, IntPtr.Zero, "EDIT", null); + return edit; + } + finally + { + handle = IntPtr.Zero; + sb.Clear(); + } } static IntPtr FindMainWindow() { - IntPtr hwnd; - - hwnd = NativeMethods.FindWindow(null, "Untitled - Notepad"); - if (hwnd != IntPtr.Zero) + NativeMethods.EnumWindows(enumWindowsDelegate, IntPtr.Zero); + return handle; + } + + static NativeMethods.EnumWindowsDelegate enumWindowsDelegate = new NativeMethods.EnumWindowsDelegate(EnumWindowsCallback); + + static bool EnumWindowsCallback(IntPtr hWnd, IntPtr lParam) + { + var result = NativeMethods.GetWindowText(hWnd, sb, sb.Capacity); + if (result < 0) { - return hwnd; + throw new Win32Exception(result); } - hwnd = NativeMethods.FindWindow(null, "*Untitled - Notepad"); - if (hwnd != IntPtr.Zero) + if (IsKnownNotepadWindow(sb.ToString())) { - return hwnd; + WindowFinder.handle = hWnd; + return false; + } + return true; + } + + [ThreadStatic] + static IntPtr handle; + + [ThreadStatic] + static StringBuilder sb; + + static bool IsKnownNotepadWindow(string titleText) + { + switch (titleText) + { + case "Untitled - Notepad": + case "*Untitled - Notepad": + return true; } - return IntPtr.Zero; + return false; } } }