Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
The selection shortcut reads the active Explorer tab, not the oldest one
KnifeLemon6b33c9e65fbb
diff --git a/src/Filee.Platform.Windows/Elevation.cs b/src/Filee.Platform.Windows/Elevation.csindex 22f2ce53..b6fd9438 100644--- a/src/Filee.Platform.Windows/Elevation.cs+++ b/src/Filee.Platform.Windows/Elevation.cs@@ -87,10 +87,10 @@ public static class Elevationobject? empty = null; // VT_EMPTYdesktop = ((IShellWindows)shellWindows).FindWindowSW(ref location, ref empty, SWC_DESKTOP, out _, SWFO_NEEDDISPATCH)?? throw new InvalidOperationException("Explorer's desktop window was not found.");- var topLevelBrowser = SID_STopLevelBrowser;- var shellBrowserId = typeof(IShellBrowser).GUID;- browser = ((IServiceProvider)desktop).QueryService(ref topLevelBrowser, ref shellBrowserId);- view = ((IShellBrowser)browser).QueryActiveShellView();+ var topLevelBrowser = ShellInterop.SID_STopLevelBrowser;+ var shellBrowserId = typeof(ShellInterop.IShellBrowser).GUID;+ browser = ((ShellInterop.IServiceProvider)desktop).QueryService(ref topLevelBrowser, ref shellBrowserId);+ view = ((ShellInterop.IShellBrowser)browser).QueryActiveShellView();var dispatchId = IID_IDispatch;background = ((IShellView)view).GetItemObject(SVGIO_BACKGROUND, ref dispatchId);// IShellFolderViewDual.Application is Explorer's IShellDispatch2: its ShellExecute runs in Explorer.@@ -181,7 +181,6 @@ public static class Elevationprivate const int SWFO_NEEDDISPATCH = 1;private const uint SVGIO_BACKGROUND = 0;private const int SW_SHOWNORMAL = 1;- private static readonly Guid SID_STopLevelBrowser = new("4C96BE40-915C-11CF-99D3-00AA004AE837");private static readonly Guid IID_IDispatch = new("00020400-0000-0000-C000-000000000046");// Only the methods Filee calls are typed; the slots before them keep the vtable order and are never called.@@ -202,33 +201,6 @@ public static class Elevationobject? FindWindowSW(ref object location, ref object? locationRoot, int windowClass, out int hwnd, int options);}- [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]- private interface IServiceProvider- {- [return: MarshalAs(UnmanagedType.IUnknown)]- object QueryService(ref Guid service, ref Guid riid);- }-- [ComImport, Guid("000214E2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]- private interface IShellBrowser- {- void GetWindow();- void ContextSensitiveHelp();- void InsertMenusSB();- void SetMenuSB();- void RemoveMenusSB();- void SetStatusTextSB();- void EnableModelessSB();- void TranslateAcceleratorSB();- void BrowseObject();- void GetViewStateStream();- void GetControlWindow();- void SendControlMsg();-- [return: MarshalAs(UnmanagedType.IUnknown)]- object QueryActiveShellView();- }-[ComImport, Guid("000214E3-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]private interface IShellView{diff --git a/src/Filee.Platform.Windows/ExplorerTabs.cs b/src/Filee.Platform.Windows/ExplorerTabs.csnew file mode 100644index 00000000..d2a19e96--- /dev/null+++ b/src/Filee.Platform.Windows/ExplorerTabs.cs@@ -0,0 +1,98 @@+// Which Shell.Application window the selection shortcut reads (issue #239). With File Explorer tabs (Windows 11)+// Shell.Application.Windows() has one entry per tab, every one with the window's HWND, in the order the tabs were+// opened; switching tabs doesn't reorder them. Each tab has its own ShellTabWindowClass child window, and only the+// active tab's is visible. The tab an entry belongs to is its shell browser's window (IShellBrowser::GetWindow).++using System.Runtime.InteropServices;+using System.Runtime.Versioning;++namespace Filee.Platform.Windows;++/// <summary>One entry of Shell.Application.Windows(): its top-level window and its tab window (0 when unknown).</summary>+internal readonly record struct ShellWindowEntry(nint TopLevel, nint Tab);++/// <summary>A ShellTabWindowClass child of an Explorer window, in z-order.</summary>+internal readonly record struct TabWindow(nint Handle, bool Visible);++internal static class ExplorerTabs+{+ private const string TabWindowClass = "ShellTabWindowClass";++ /// <summary>+ /// The active tab among the tab windows of one Explorer window: the visible one, else the first in z-order+ /// (the active tab is on top). 0 when the window has no tab windows (the desktop, other windows).+ /// </summary>+ public static nint PickActiveTab(IEnumerable<TabWindow> tabs)+ {+ nint first = 0;+ foreach (var tab in tabs)+ {+ if (tab.Visible)+ return tab.Handle;+ if (first == 0)+ first = tab.Handle;+ }+ return first;+ }++ /// <summary>+ /// The entries to read the selection from, in order. Only entries of the foreground window count. When one of them+ /// is the active tab, it is the only one: another tab's selection, even a stale one, is never what the user means.+ /// Without tabs, or when no entry gives out its tab window, every entry of the window is tried in order.+ /// </summary>+ public static IReadOnlyList<int> Candidates(IReadOnlyList<ShellWindowEntry> entries, nint foreground, nint activeTab)+ {+ var sameWindow = new List<int>();+ for (var i = 0; i < entries.Count; i++)+ {+ if (entries[i].TopLevel != foreground)+ continue;+ if (activeTab != 0 && entries[i].Tab == activeTab)+ return [i];+ sameWindow.Add(i);+ }+ return sameWindow;+ }++ /// <summary>The active tab window of an Explorer window, or 0.</summary>+ [SupportedOSPlatform("windows")]+ public static nint ActiveTabOf(nint topLevel) => PickActiveTab(TabWindowsOf(topLevel));++ [SupportedOSPlatform("windows")]+ private static IEnumerable<TabWindow> TabWindowsOf(nint topLevel)+ {+ nint child = 0;+ while ((child = NativeMethods.FindWindowEx(topLevel, child, TabWindowClass, null)) != 0)+ yield return new TabWindow(child, NativeMethods.IsWindowVisible(child));+ }++ /// <summary>The tab window of one Shell.Application window (an IWebBrowser2), or 0 when it doesn't say.</summary>+ [SupportedOSPlatform("windows")]+ public static nint TabOf(object window)+ {+ object? browser = null;+ try+ {+ if (window is not ShellInterop.IServiceProvider provider)+ return 0;+ var service = ShellInterop.SID_STopLevelBrowser;+ var shellBrowserId = typeof(ShellInterop.IShellBrowser).GUID;+ browser = provider.QueryService(ref service, ref shellBrowserId);+ return browser is ShellInterop.IShellBrowser shellBrowser && shellBrowser.GetWindow(out var hwnd) >= 0 ? hwnd : 0;+ }+ catch (COMException)+ {+ return 0;+ }+ catch (InvalidCastException)+ {+ return 0;+ }+ finally+ {+ // Not the final release: the browser may be the same COM object as the window, which is still used.+ if (browser is not null && Marshal.IsComObject(browser))+ Marshal.ReleaseComObject(browser);+ }+ }+}diff --git a/src/Filee.Platform.Windows/NativeMethods.cs b/src/Filee.Platform.Windows/NativeMethods.csindex 6db6b0e0..8cd71e94 100644--- a/src/Filee.Platform.Windows/NativeMethods.cs+++ b/src/Filee.Platform.Windows/NativeMethods.cs@@ -118,6 +118,13 @@ internal static partial class NativeMethods[LibraryImport("user32.dll")]public static partial nint GetShellWindow();+ [LibraryImport("user32.dll", EntryPoint = "FindWindowExW", StringMarshalling = StringMarshalling.Utf16)]+ public static partial nint FindWindowEx(nint parent, nint childAfter, string? className, string? windowName);++ [LibraryImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ public static partial bool IsWindowVisible(nint hwnd);+public const uint MB_OK = 0x0, MB_ICONWARNING = 0x30, MB_SETFOREGROUND = 0x10000, MB_TOPMOST = 0x40000;[LibraryImport("user32.dll", EntryPoint = "MessageBoxW", StringMarshalling = StringMarshalling.Utf16)]diff --git a/src/Filee.Platform.Windows/ShellInterop.cs b/src/Filee.Platform.Windows/ShellInterop.csnew file mode 100644index 00000000..8f703ac1--- /dev/null+++ b/src/Filee.Platform.Windows/ShellInterop.cs@@ -0,0 +1,43 @@+// COM interfaces of Explorer's shell browser, shared by the de-elevated restart (Elevation) and the selection lookup+// (ExplorerTabs). Only the methods Filee calls are typed; the slots before them keep the vtable order and are never+// called.++using System.Runtime.InteropServices;++namespace Filee.Platform.Windows;++internal static class ShellInterop+{+ /// <summary>Service id of the browser that hosts a shell view: the Explorer window, or with tabs the tab.</summary>+ public static readonly Guid SID_STopLevelBrowser = new("4C96BE40-915C-11CF-99D3-00AA004AE837");++ [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IServiceProvider+ {+ [return: MarshalAs(UnmanagedType.IUnknown)]+ object QueryService(ref Guid service, ref Guid riid);+ }++ [ComImport, Guid("000214E2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IShellBrowser+ {+ /// <summary>IOleWindow::GetWindow: with Explorer tabs, the tab's own ShellTabWindowClass window.</summary>+ [PreserveSig]+ int GetWindow(out nint hwnd);++ void ContextSensitiveHelp();+ void InsertMenusSB();+ void SetMenuSB();+ void RemoveMenusSB();+ void SetStatusTextSB();+ void EnableModelessSB();+ void TranslateAcceleratorSB();+ void BrowseObject();+ void GetViewStateStream();+ void GetControlWindow();+ void SendControlMsg();++ [return: MarshalAs(UnmanagedType.IUnknown)]+ object QueryActiveShellView();+ }+}diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.csindex 34337327..9466305d 100644--- a/src/Filee.Platform.Windows/WindowsPlatformServices.cs+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs@@ -77,9 +77,12 @@ public sealed class WindowsPlatformServices : IPlatformServicespublic IReadOnlyList<string> GetFileManagerSelection(){var foreground = NativeMethods.GetForegroundWindow();- if (foreground == 0)- return [];+ return foreground == 0 ? [] : SelectionOf(foreground);+ }+ /// <summary>The selected files of an Explorer window; with tabs, of its active tab (see <see cref="ExplorerTabs"/>).</summary>+ internal static IReadOnlyList<string> SelectionOf(nint foreground)+ {var type = Type.GetTypeFromProgID("Shell.Application");if (type is null)return [];@@ -91,17 +94,37 @@ public sealed class WindowsPlatformServices : IPlatformServicesdynamic windows = shell.Windows();int count = windows.Count;- // With Explorer tabs (Windows 11) several entries share one HWND. The active tab is the one- // that has a selection in practice, so take the first matching window with selected items.+ // With Explorer tabs (Windows 11) every tab is an entry with the window's HWND: find the active one.+ var activeTab = ExplorerTabs.ActiveTabOf(foreground);+ var found = new List<object?>(count);+ var entries = new List<ShellWindowEntry>(count);for (var i = 0; i < count; i++){- dynamic? window = windows.Item(i);+ object? window = null;+ nint topLevel = 0, tab = 0;+ try+ {+ window = windows.Item(i);+ if (window is not null)+ {+ topLevel = (nint)(long)((dynamic)window).HWND;+ if (topLevel == foreground && activeTab != 0)+ tab = ExplorerTabs.TabOf(window);+ }+ }+ catch (COMException) { }+ catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { } // e.g. Internet Explorer windows+ found.Add(window);+ entries.Add(new ShellWindowEntry(topLevel, tab));+ }++ foreach (var i in ExplorerTabs.Candidates(entries, foreground, activeTab))+ {+ dynamic? window = found[i];if (window is null)continue;try{- if ((nint)(long)window.HWND != foreground)- continue;dynamic items = window.Document.SelectedItems();var paths = new List<string>();foreach (dynamic item in items)diff --git a/tests/Filee.Platform.Tests/ExplorerTabsTests.cs b/tests/Filee.Platform.Tests/ExplorerTabsTests.csnew file mode 100644index 00000000..059c465b--- /dev/null+++ b/tests/Filee.Platform.Tests/ExplorerTabsTests.cs@@ -0,0 +1,53 @@+using Filee.Platform.Windows;++namespace Filee.Platform.Tests;++/// <summary>The selection shortcut reads the active Explorer tab, not the oldest tab of the window (#239).</summary>+public sealed class ExplorerTabsTests+{+ private const nint Window = 0x1000, OtherWindow = 0x2000;+ private const nint TabA = 0x11, TabB = 0x12, TabC = 0x13;++ [Fact]+ public void The_active_tab_is_the_only_entry_read_among_tabs_of_one_window()+ {+ // Shell.Application lists the tabs in the order they were opened, all with the window's HWND.+ ShellWindowEntry[] entries = [new(OtherWindow, 0x21), new(Window, TabA), new(Window, TabB), new(Window, TabC)];++ Assert.Equal([2], ExplorerTabs.Candidates(entries, Window, TabB));+ Assert.Equal([3], ExplorerTabs.Candidates(entries, Window, TabC));+ Assert.Equal([1], ExplorerTabs.Candidates(entries, Window, TabA));+ }++ [Fact]+ public void A_single_window_is_read_as_before()+ {+ ShellWindowEntry[] entries = [new(OtherWindow, 0x21), new(Window, TabA)];++ Assert.Equal([1], ExplorerTabs.Candidates(entries, Window, TabA));+ // No tab window found (the desktop, Windows 10 builds that don't give it out): every entry of the window.+ Assert.Equal([1], ExplorerTabs.Candidates(entries, Window, 0));+ }++ [Fact]+ public void Without_a_matching_tab_every_entry_of_the_window_is_tried_in_order()+ {+ // The tabs didn't give out their windows (0), or none of them is the visible one: the old lookup.+ ShellWindowEntry[] unknown = [new(Window, 0), new(OtherWindow, 0), new(Window, 0)];+ ShellWindowEntry[] noMatch = [new(Window, TabA), new(Window, TabB)];++ Assert.Equal([0, 2], ExplorerTabs.Candidates(unknown, Window, TabC));+ Assert.Equal([0, 1], ExplorerTabs.Candidates(noMatch, Window, TabC));+ Assert.Empty(ExplorerTabs.Candidates(noMatch, OtherWindow, TabA));+ Assert.Empty(ExplorerTabs.Candidates([], Window, TabA));+ }++ [Fact]+ public void The_active_tab_window_is_the_visible_one_else_the_topmost()+ {+ Assert.Equal(TabB, ExplorerTabs.PickActiveTab([new(TabA, false), new(TabB, true), new(TabC, false)]));+ Assert.Equal(TabA, ExplorerTabs.PickActiveTab([new(TabA, true), new(TabB, false)]));+ Assert.Equal(TabA, ExplorerTabs.PickActiveTab([new(TabA, false), new(TabB, false)]));+ Assert.Equal(0, ExplorerTabs.PickActiveTab([]));+ }+}