// ==WindhawkMod== // @id taskbar-notification-icon-spacing // @name Taskbar tray icon spacing and grid // @description Reduce or increase the spacing between tray icons on the taskbar, optionally have a grid of tray icons (Windows 11 only) // @version 1.5 // @author m417z // @github https://github.com/m417z // @twitter https://twitter.com/m417z // @homepage https://m417z.com/ // @include explorer.exe // @architecture x86-64 // @compilerOptions -lole32 -loleaut32 -lruntimeobject -lversion // ==/WindhawkMod== // Source code is published under The GNU General Public License v3.0. // // For bug reports and feature requests, please open an issue here: // https://github.com/ramensoftware/windhawk-mods/issues // // For pull requests, development takes place here: // https://github.com/m417z/my-windhawk-mods // ==WindhawkModReadme== /* # Taskbar tray icon spacing and grid Reduce or increase the spacing between tray icons on the taskbar, optionally have a grid of tray icons. Only Windows 11 version 22H2 or newer is currently supported. For older Windows versions check out [7+ Taskbar Tweaker](https://tweaker.ramensoftware.com/). ![Tray icon width: 32](https://i.imgur.com/BGWZf6x.png) \ *Tray icon width: 32 (Windows 11 default)* ![Tray icon width: 24](https://i.imgur.com/EIyWATk.png) \ *Tray icon width: 24* ![Tray icon width: 18](https://i.imgur.com/MPi1F3m.png) \ *Tray icon width: 18* ![Tray icon width: 18, rows: 2](https://i.imgur.com/zOUUTmb.png) \ *Tray icon width: 18, rows: 2* ## Vertical taskbar With the native vertical taskbar of newer Windows 11 builds, the tray icon width sets the height of the tray icons, and the tray icon rows set the number of columns of the grid of tray icons. With a single row, the tray icons are arranged in a grid when the taskbar is wide enough. */ // ==/WindhawkModReadme== // ==WindhawkModSettings== /* - notificationIconWidth: 24 $name: Tray icon width $description: >- Windows 11 default: 32 With the native vertical taskbar, sets the tray icon height. - notificationIconRows: 1 $name: Tray icon rows $description: >- Allows having a grid of tray icons. With the native vertical taskbar, sets the number of columns. With 1, the tray icons are arranged in a grid when the taskbar is wide enough, and the number of columns depends on the tray icon width. - gridArrangement: rowFirstLeftToRight $name: Grid arrangement $description: >- The order in which tray icons are arranged when using multiple rows. Not used with the native vertical taskbar. Row-first fills each row before moving to the next. Column-first fills each column before moving to the next. Examples with icons A-G and 2 rows: Row-first, left-to-right: A B C D E F G Column-first, top-to-bottom: A C E G B D F Row-first, bottom row first: E F G A B C D Column-first, bottom-to-top: B D F A C E G Column-first, bottom-to-top, right-to-left: _ F D B G E C A $options: - rowFirstLeftToRight: Row-first, left-to-right - columnFirstTopToBottom: Column-first, top-to-bottom - rowFirstBottomRowFirst: Row-first, bottom row first - columnFirstBottomToTop: Column-first, bottom-to-top - columnFirstBottomToTopRightToLeft: >- Column-first, bottom-to-top, right-to-left - overflowIconWidth: 32 $name: Tray overflow icon width $description: >- The width of icons that appear in the overflow popup when clicking on the chevron icon. Windows 11 default: 40 - overflowIconsPerRow: 5 $name: Tray overflow icons per row $description: >- The maximum amount of icons per row in the overflow popup. Windows 11 default: 5 */ // ==/WindhawkModSettings== #include #include #include #include #include #include #include #undef GetCurrentTime #include #include #include #include #include #include using namespace winrt::Windows::UI::Xaml; enum class GridArrangement { rowFirstLeftToRight, columnFirstTopToBottom, rowFirstBottomRowFirst, columnFirstBottomToTop, columnFirstBottomToTopRightToLeft, }; struct { int notificationIconWidth; int notificationIconRows; GridArrangement gridArrangement; int overflowIconWidth; int overflowIconsPerRow; } g_settings; std::atomic g_systemTrayModuleHooked; std::atomic g_unloading; using FrameworkElementLoadedEventRevoker = winrt::impl::event_revoker< IFrameworkElement, &winrt::impl::abi::type::remove_Loaded>; // Only accessed from the taskbar thread, which is also where it's cleared in // ApplySettings, rather than by the destructor at process exit. [[clang::no_destroy]] std::optional< std::list> g_autoRevokerList{ std::in_place}; winrt::weak_ref g_notificationAreaIconsStackPanel; winrt::weak_ref g_overflowRootGrid; HWND FindCurrentProcessTaskbarWnd() { HWND hTaskbarWnd = nullptr; EnumWindows( [](HWND hWnd, LPARAM lParam) -> BOOL { DWORD dwProcessId; WCHAR className[32]; if (GetWindowThreadProcessId(hWnd, &dwProcessId) && dwProcessId == GetCurrentProcessId() && GetClassName(hWnd, className, ARRAYSIZE(className)) && _wcsicmp(className, L"Shell_TrayWnd") == 0) { *reinterpret_cast(lParam) = hWnd; return FALSE; } return TRUE; }, reinterpret_cast(&hTaskbarWnd)); return hTaskbarWnd; } FrameworkElement FindParentByName(FrameworkElement element, PCWSTR name) { auto parent = element; while (true) { parent = Media::VisualTreeHelper::GetParent(parent) .try_as(); if (!parent) { return nullptr; } if (parent.Name() == name) { return parent; } } } bool IsChildOfElementByName(FrameworkElement element, PCWSTR name) { return !!FindParentByName(element, name); } FrameworkElement FindParentByClassName(FrameworkElement element, PCWSTR className) { auto parent = element; while (true) { parent = Media::VisualTreeHelper::GetParent(parent) .try_as(); if (!parent) { return nullptr; } if (winrt::get_class_name(parent) == className) { return parent; } } } bool IsChildOfElementByClassName(FrameworkElement element, PCWSTR className) { return !!FindParentByClassName(element, className); } FrameworkElement EnumChildElements( FrameworkElement element, std::function enumCallback) { int childrenCount = Media::VisualTreeHelper::GetChildrenCount(element); for (int i = 0; i < childrenCount; i++) { auto child = Media::VisualTreeHelper::GetChild(element, i) .try_as(); if (!child) { Wh_Log(L"Failed to get child %d of %d", i + 1, childrenCount); continue; } if (enumCallback(child)) { return child; } } return nullptr; } FrameworkElement FindChildByName(FrameworkElement element, PCWSTR name) { return EnumChildElements(element, [name](FrameworkElement child) { return child.Name() == name; }); } FrameworkElement FindChildByClassName(FrameworkElement element, PCWSTR className) { return EnumChildElements(element, [className](FrameworkElement child) { return winrt::get_class_name(child) == className; }); } template T FindDescendant(DependencyObject element) { int childrenCount = Media::VisualTreeHelper::GetChildrenCount(element); for (int i = 0; i < childrenCount; i++) { auto child = Media::VisualTreeHelper::GetChild(element, i); if (auto result = child.try_as()) { return result; } if (auto result = FindDescendant(child)) { return result; } } return nullptr; } FrameworkElement FindDescendantByName(DependencyObject element, PCWSTR name) { int childrenCount = Media::VisualTreeHelper::GetChildrenCount(element); for (int i = 0; i < childrenCount; i++) { auto child = Media::VisualTreeHelper::GetChild(element, i); auto childElement = child.try_as(); if (childElement && childElement.Name() == name) { return childElement; } if (auto result = FindDescendantByName(child, name)) { return result; } } return nullptr; } bool IsCurrentVisualState(FrameworkElement element, PCWSTR groupName, PCWSTR stateName) { for (const auto& group : VisualStateManager::GetVisualStateGroups(element)) { if (group.Name() == groupName) { auto currentState = group.CurrentState(); return currentState && currentState.Name() == stateName; } } return false; } // The native vertical taskbar switches the tray to a vertical layout with a // visual state. A tray which is rotated as a whole keeps the horizontal layout. bool IsVerticalSystemTray(FrameworkElement systemTrayFrameGrid) { return IsCurrentVisualState(systemTrayFrameGrid, L"OrientationStates", L"VerticalOrientation"); } void ApplyNotifyIconViewOverflowStyle(FrameworkElement notifyIconViewElement, int width) { Wh_Log(L"Setting MinWidth=%d for NotifyIconView (overflow)", width); notifyIconViewElement.MinWidth(width); Wh_Log(L"Setting Height=%d for NotifyIconView (overflow)", width); notifyIconViewElement.Height(width); FrameworkElement child = notifyIconViewElement; if ((child = FindChildByName(child, L"ContainerGrid")) && (child = FindChildByName(child, L"ContentPresenter")) && (child = FindChildByName(child, L"ContentGrid"))) { EnumChildElements(child, [](FrameworkElement child) { auto className = winrt::get_class_name(child); if (className == L"SystemTray.ImageIconContent") { auto containerGrid = FindChildByName(child, L"ContainerGrid") .try_as(); if (containerGrid) { Wh_Log(L"Setting Padding=0 for ContainerGrid"); containerGrid.Padding(Thickness{}); } } else { Wh_Log(L"Unsupported class name %s of child", className.c_str()); } return false; }); } } // With a vertical tray, the width is the extent of the icon along the taskbar, // its height. void ApplyNotifyIconViewStyle(FrameworkElement notifyIconViewElement, int width, bool vertical = false) { if (vertical) { Wh_Log(L"Setting MinHeight=%d for NotifyIconView", width); notifyIconViewElement.MinHeight(width); // The icon fills its column, which can be narrower than the minimum // width of the icon style. if (g_unloading) { notifyIconViewElement.as().ClearValue( FrameworkElement::MinWidthProperty()); } else { notifyIconViewElement.MinWidth(0); } } else { Wh_Log(L"Setting MinWidth=%d for NotifyIconView", width); notifyIconViewElement.MinWidth(width); } FrameworkElement child = notifyIconViewElement; if ((child = FindChildByName(child, L"ContainerGrid")) && (child = FindChildByName(child, L"ContentPresenter")) && (child = FindChildByName(child, L"ContentGrid"))) { EnumChildElements(child, [width](FrameworkElement child) { auto className = winrt::get_class_name(child); if (className == L"SystemTray.TextIconContent" || className == L"SystemTray.ImageIconContent") { auto containerGrid = FindChildByName(child, L"ContainerGrid") .try_as(); if (containerGrid) { Wh_Log(L"Setting Padding=0 for ContainerGrid"); containerGrid.Padding(Thickness{}); } } else if (className == L"SystemTray.LanguageTextIconContent") { child.Width(std::numeric_limits::quiet_NaN()); // Every language has a different width. ENG is 24. Default // width is 44. double minWidth = width + 12; Wh_Log(L"Setting MinWidth=%f for LanguageTextIconContent", minWidth); child.MinWidth(minWidth); } else { Wh_Log(L"Unsupported class name %s of child", className.c_str()); } return false; }); } } void ApplyNotifyIconsStackPanelGridStyle(FrameworkElement stackPanel, int rows, int width) { double itemHeight = 0; if (rows > 1) { double stackPanelHeight = stackPanel.ActualHeight(); double gap = stackPanelHeight - 16 * rows; double gapPerItem = std::fmax(gap, 0.0) / (rows + 1); // Force the gap to be an even number to prevent blurry icons. int gapPerItemEven = static_cast(gapPerItem) / 2 * 2; itemHeight = 16 + gapPerItemEven; } // Count children first for row-first arrangements. int childCount = Media::VisualTreeHelper::GetChildrenCount(stackPanel); int cols = (childCount + rows - 1) / rows; GridArrangement arrangement = g_settings.gridArrangement; int indexIter = 0; EnumChildElements(stackPanel, [width, rows, itemHeight, cols, arrangement, &indexIter](FrameworkElement child) { int index = indexIter++; auto childClassName = winrt::get_class_name(child); if (childClassName != L"Windows.UI.Xaml.Controls.ContentPresenter") { Wh_Log(L"Unsupported class name %s of child", childClassName.c_str()); return false; } if (rows > 1) { child.Height(itemHeight); int col, row; switch (arrangement) { case GridArrangement::rowFirstLeftToRight: col = index % cols; row = index / cols; break; case GridArrangement::columnFirstTopToBottom: col = index / rows; row = index % rows; break; case GridArrangement::rowFirstBottomRowFirst: col = index % cols; row = (rows - 1) - (index / cols); break; case GridArrangement::columnFirstBottomToTop: col = index / rows; row = (rows - 1) - (index % rows); break; case GridArrangement::columnFirstBottomToTopRightToLeft: col = (cols - 1) - (index / rows); row = (rows - 1) - (index % rows); break; } Media::TranslateTransform transform; int xOffset = width * (col - index); transform.X(xOffset); double yOffset = itemHeight * row - itemHeight * (rows - 1) / 2; transform.Y(yOffset); child.RenderTransform(transform); } else { auto childDp = child.as(); childDp.ClearValue(FrameworkElement::HeightProperty()); childDp.ClearValue(UIElement::RenderTransformProperty()); } return false; }); if (rows > 1) { int desiredWidth = width * ((indexIter + rows - 1) / rows); stackPanel.Width(desiredWidth); } else { stackPanel.as().ClearValue( FrameworkElement::WidthProperty()); } g_notificationAreaIconsStackPanel = stackPanel; } void ApplyNotifyIconsStackPanelGridStyleOfIcon( FrameworkElement notifyIconViewElement, int rows, int width) { auto contentPresenter = Media::VisualTreeHelper::GetParent(notifyIconViewElement) .try_as(); if (!contentPresenter || winrt::get_class_name(contentPresenter) != L"Windows.UI.Xaml.Controls.ContentPresenter") { return; } auto stackPanel = Media::VisualTreeHelper::GetParent(contentPresenter) .try_as(); if (!stackPanel || winrt::get_class_name(stackPanel) != L"Windows.UI.Xaml.Controls.StackPanel") { return; } ApplyNotifyIconsStackPanelGridStyle(stackPanel, rows, width); } // A vertical tray which is wide enough arranges the icons in a wrap grid, with // rows of a fixed height, 44 by default. void ApplyNotifyIconsWrapGridStyle(Controls::WrapGrid wrapGrid, int width) { int itemHeight = g_unloading ? 44 : width; Wh_Log(L"Setting ItemHeight=%d for WrapGrid", itemHeight); wrapGrid.ItemHeight(itemHeight); } void ApplyNotifyIconsWrapGridStyleOfIcon(FrameworkElement notifyIconViewElement, int width) { auto contentPresenter = Media::VisualTreeHelper::GetParent(notifyIconViewElement) .try_as(); if (!contentPresenter) { return; } auto wrapGrid = Media::VisualTreeHelper::GetParent(contentPresenter) .try_as(); if (!wrapGrid) { return; } ApplyNotifyIconsWrapGridStyle(wrapGrid, width); } // The rows of a horizontal tray are the columns of a vertical one, as with a // tray which is rotated as a whole. The columns split the frame width. With a // single row, as many columns are used as fit an icon with 8 pixels of padding // on each side. That's 48 for the default icon width of 32, the width of the // vertical taskbar without labels. bool ApplyNotifyIconsWrapGridColumns( Controls::ItemsControl notificationAreaIcons, int rows, int width) { auto wrapGrid = notificationAreaIcons.ItemsPanelRoot().try_as(); auto systemTrayFrame = FindParentByClassName(notificationAreaIcons, L"SystemTray.SystemTrayFrame"); if (!wrapGrid || !systemTrayFrame) { return false; } double frameWidth = systemTrayFrame.Width(); if (!(frameWidth > 0)) { return false; } int maxColumns; if (rows > 1) { // Columns narrower than a 16 pixel icon with the edge inset of the // first and last columns would overlap. maxColumns = std::min(rows, (int)(frameWidth / 20)); } else { maxColumns = (int)(frameWidth / (width + 16)); } int itemCount = notificationAreaIcons.Items().Size(); int columns = std::clamp(itemCount, 1, std::max(1, maxColumns)); double scale = 1; if (auto xamlRoot = wrapGrid.XamlRoot()) { scale = xamlRoot.RasterizationScale(); } double itemWidth = std::max(1.0, std::floor(frameWidth / columns * scale) / scale); Wh_Log(L"Setting MaximumRowsOrColumns=%d, ItemWidth=%f for WrapGrid", columns, itemWidth); wrapGrid.MaximumRowsOrColumns(columns); wrapGrid.ItemWidth(itemWidth); return true; } // Like the taskbar, insets the first and last icons of each row from the frame // edges, but for the columns of the grid instead of the default ones. bool ApplyNotifyIconsWrapGridEdgePadding(Controls::ItemsControl itemsControl, unsigned int itemCount) { auto wrapGrid = itemsControl.ItemsPanelRoot().try_as(); auto systemTrayFrame = FindParentByClassName(itemsControl, L"SystemTray.SystemTrayFrame"); if (!wrapGrid || !systemTrayFrame) { return false; } double frameWidth = systemTrayFrame.Width(); double itemWidth = wrapGrid.ItemWidth(); int maximumColumns = wrapGrid.MaximumRowsOrColumns(); if (!(frameWidth > 0) || !(itemWidth > 0) || maximumColumns < 1) { return false; } constexpr double kInset = 4; unsigned int columns = maximumColumns; unsigned int rows = (itemCount + columns - 1) / columns; double leftover = std::max(frameWidth - itemWidth * columns, 0.0); for (unsigned int i = 0; i < itemCount; i++) { auto container = itemsControl.ContainerFromIndex(static_cast(i)); if (!container) { continue; } auto control = FindDescendant(container); if (!control) { continue; } unsigned int row = i / columns; unsigned int column = i % columns; unsigned int rowItemCount = row == rows - 1 ? itemCount - row * columns : columns; Thickness padding{}; if (column == 0) { padding.Left = kInset; } if (column == rowItemCount - 1) { double rowLeftover = rowItemCount == columns ? leftover : 0; padding.Right = std::max(kInset - rowLeftover, 0.0); } control.Padding(padding); // The content of icons with a background is inset with the background. auto contentGrid = FindDescendantByName(control, L"ContentGrid"); if (!contentGrid) { continue; } if (FindDescendantByName(control, L"BackgroundBorder")) { contentGrid.Margin(padding); } else { contentGrid.as().ClearValue( FrameworkElement::MarginProperty()); } } return true; } // The compact layout of a vertical tray, used when the taskbar doesn't show // labels, stacks the icons in a single column. For a grid, the icons get the // wrap grid of the detailed layout, and the rest of the compact layout is kept. // Returns whether the panel was changed. bool ApplyNotifyIconsCompactLayoutPanel( FrameworkElement systemTrayFrameGrid, Controls::ItemsControl notificationAreaIcons, int rows) { if (!IsCurrentVisualState(systemTrayFrameGrid, L"LayoutStates", L"VerticalCompactLayout")) { return false; } // The panels which the layout states set. auto resources = Application::Current().Resources(); auto compactPanel = resources .TryLookup(winrt::box_value(L"VerticalNotificationAreaIconsPanel")) .try_as(); auto detailedPanel = resources .TryLookup(winrt::box_value(L"DetailedNotificationAreaIconsPanel")) .try_as(); if (!compactPanel || !detailedPanel) { Wh_Log(L"Notification area icons panel resources not found"); return false; } bool hasDetailedPanel = notificationAreaIcons.ItemsPanel() == detailedPanel; if ((rows > 1) == hasDetailedPanel) { return false; } Wh_Log(L"Setting %s panel for NotificationAreaIcons", rows > 1 ? L"detailed" : L"compact"); notificationAreaIcons.ItemsPanel(rows > 1 ? detailedPanel : compactPanel); return true; } bool ApplyNotifyIconsStyle(FrameworkElement notificationAreaIcons, int rows, int width, bool vertical) { FrameworkElement itemsPanel = nullptr; FrameworkElement child = notificationAreaIcons; if ((child = FindChildByClassName( child, L"Windows.UI.Xaml.Controls.ItemsPresenter")) && (child = EnumChildElements(child, [](FrameworkElement child) { return !!child.try_as(); }))) { itemsPanel = child; } if (!itemsPanel) { return false; } EnumChildElements(itemsPanel, [width, vertical](FrameworkElement child) { auto childClassName = winrt::get_class_name(child); if (childClassName != L"Windows.UI.Xaml.Controls.ContentPresenter") { Wh_Log(L"Unsupported class name %s of child", childClassName.c_str()); return false; } FrameworkElement notifyIconViewElement = FindChildByName(child, L"NotifyItemIcon"); if (!notifyIconViewElement) { Wh_Log(L"Failed to get notifyIconViewElement of child"); return false; } ApplyNotifyIconViewStyle(notifyIconViewElement, width, vertical); return false; }); if (!vertical) { ApplyNotifyIconsStackPanelGridStyle(itemsPanel, rows, width); } else if (auto wrapGrid = itemsPanel.try_as()) { ApplyNotifyIconsWrapGridStyle(wrapGrid, width); auto itemsControl = notificationAreaIcons.try_as(); if (itemsControl && ApplyNotifyIconsWrapGridColumns(itemsControl, rows, width)) { ApplyNotifyIconsWrapGridEdgePadding(itemsControl, itemsControl.Items().Size()); } } return true; } void ApplySystemTrayIconStyle(FrameworkElement systemTrayIconElement, int width) { Wh_Log(L"Setting width %d for SystemTrayIcon", width); FrameworkElement child = systemTrayIconElement; if ((child = FindChildByName(child, L"ContainerGrid")) && (child = FindChildByName(child, L"ContentGrid")) && (child = FindChildByClassName(child, L"SystemTray.TextIconContent")) && (child = FindChildByName(child, L"ContainerGrid"))) { auto childControl = child.try_as(); if (childControl) { int newPadding = 4; if (width > 32) { newPadding = (8 + width - 32) / 2; } else if (width < 24) { newPadding = (8 + width - 24) / 2; if (newPadding < 0) { newPadding = 0; } } Wh_Log(L"Setting Padding=%d for ContainerGrid", newPadding); childControl.Padding(Thickness{ .Left = static_cast(newPadding), .Right = static_cast(newPadding), }); } } } bool ApplyControlCenterButtonStyle(FrameworkElement controlCenterButton, int width) { FrameworkElement stackPanel = nullptr; FrameworkElement child = controlCenterButton; if ((child = FindChildByClassName(child, L"Windows.UI.Xaml.Controls.Grid")) && (child = FindChildByName(child, L"ContentPresenter")) && (child = FindChildByClassName( child, L"Windows.UI.Xaml.Controls.ItemsPresenter")) && (child = FindChildByClassName( child, L"Windows.UI.Xaml.Controls.StackPanel"))) { stackPanel = child; } if (!stackPanel) { return false; } EnumChildElements(stackPanel, [width](FrameworkElement child) { auto childClassName = winrt::get_class_name(child); if (childClassName != L"Windows.UI.Xaml.Controls.ContentPresenter") { Wh_Log(L"Unsupported class name %s of child", childClassName.c_str()); return false; } FrameworkElement systemTrayIconElement = FindChildByName(child, L"SystemTrayIcon"); if (!systemTrayIconElement) { Wh_Log(L"Failed to get SystemTrayIcon of child"); return false; } ApplySystemTrayIconStyle(systemTrayIconElement, width); return false; }); return true; } bool ApplyIconStackStyle(PCWSTR containerName, FrameworkElement container, int width) { FrameworkElement stackPanel = nullptr; FrameworkElement child = container; if ((child = FindChildByName(child, L"Content")) && (child = FindChildByName(child, L"IconStack")) && (child = FindChildByClassName( child, L"Windows.UI.Xaml.Controls.ItemsPresenter")) && (child = FindChildByClassName( child, L"Windows.UI.Xaml.Controls.StackPanel"))) { stackPanel = child; } if (!stackPanel) { return false; } EnumChildElements(stackPanel, [containerName, width](FrameworkElement child) { auto childClassName = winrt::get_class_name(child); if (childClassName != L"Windows.UI.Xaml.Controls.ContentPresenter") { Wh_Log(L"Unsupported class name %s of child", childClassName.c_str()); return false; } if (wcscmp(containerName, L"NotifyIconStack") == 0) { FrameworkElement systemTrayChevronIconViewElement = FindChildByClassName(child, L"SystemTray.ChevronIconView"); if (!systemTrayChevronIconViewElement) { Wh_Log(L"Failed to get SystemTray.ChevronIconView of child"); return false; } ApplyNotifyIconViewStyle(systemTrayChevronIconViewElement, width); } else { FrameworkElement systemTrayIconElement = FindChildByName(child, L"SystemTrayIcon"); if (!systemTrayIconElement) { Wh_Log(L"Failed to get SystemTrayIcon of child"); return false; } ApplyNotifyIconViewStyle(systemTrayIconElement, width); } return false; }); return true; } // On newer builds, the XAML root content is the taskbar frame, and the tray // frame is an item of its repeater. FrameworkElement FindSystemTrayFrame(FrameworkElement xamlRootContent) { if (winrt::get_class_name(xamlRootContent) != L"Taskbar.TaskbarFrame") { return FindChildByClassName(xamlRootContent, L"SystemTray.SystemTrayFrame"); } FrameworkElement child = xamlRootContent; if (!(child = FindChildByName(child, L"RootGrid")) || !(child = FindChildByName(child, L"TaskbarFrameRepeater"))) { return nullptr; } FrameworkElement systemTrayFrame = nullptr; EnumChildElements(child, [&systemTrayFrame](FrameworkElement item) { if (winrt::get_class_name(item) != L"Taskbar.TaskbarExtensionElement") { return false; } auto extensionElement = item.try_as(); auto content = extensionElement ? extensionElement.Content().try_as() : nullptr; if (!content || winrt::get_class_name(content) != L"SystemTray.SystemTrayFrame") { return false; } systemTrayFrame = content; return true; }); return systemTrayFrame; } bool ApplyStyle(XamlRoot xamlRoot, int rows, int width) { FrameworkElement systemTrayFrameGrid = nullptr; FrameworkElement child = xamlRoot.Content().try_as(); if (child && (child = FindSystemTrayFrame(child)) && (child = FindChildByName(child, L"SystemTrayFrameGrid"))) { systemTrayFrameGrid = child; } if (!systemTrayFrameGrid) { return false; } bool vertical = IsVerticalSystemTray(systemTrayFrameGrid); bool somethingSucceeded = false; FrameworkElement notificationAreaIcons = FindChildByName(systemTrayFrameGrid, L"NotificationAreaIcons"); if (notificationAreaIcons) { auto itemsControl = notificationAreaIcons.try_as(); if (vertical && itemsControl && ApplyNotifyIconsCompactLayoutPanel(systemTrayFrameGrid, itemsControl, rows)) { // Creates the panel, which is styled below. itemsControl.UpdateLayout(); } somethingSucceeded |= ApplyNotifyIconsStyle(notificationAreaIcons, rows, width, vertical); } // The heights of the other icons in a vertical tray are set by the taskbar // for each layout. if (vertical) { return somethingSucceeded; } FrameworkElement controlCenterButton = FindChildByName(systemTrayFrameGrid, L"ControlCenterButton"); if (controlCenterButton) { somethingSucceeded |= ApplyControlCenterButtonStyle(controlCenterButton, width); } for (PCWSTR containerName : { L"NotifyIconStack", L"MainStack", L"NonActivatableStack", }) { FrameworkElement container = FindChildByName(systemTrayFrameGrid, containerName); if (container) { somethingSucceeded |= ApplyIconStackStyle(containerName, container, width); } } return somethingSucceeded; } using IconView_IconView_t = void*(WINAPI*)(void* pThis); IconView_IconView_t IconView_IconView_Original; void* WINAPI IconView_IconView_Hook(void* pThis) { Wh_Log(L">"); void* ret = IconView_IconView_Original(pThis); // A handler registered while unloading could outlive the mod. if (g_unloading) { return ret; } FrameworkElement iconView = nullptr; ((IUnknown**)pThis)[1]->QueryInterface(winrt::guid_of(), winrt::put_abi(iconView)); if (!iconView) { return ret; } g_autoRevokerList->emplace_back(); auto autoRevokerIt = g_autoRevokerList->end(); --autoRevokerIt; *autoRevokerIt = iconView.Loaded( winrt::auto_revoke_t{}, [autoRevokerIt](winrt::Windows::Foundation::IInspectable const& sender, RoutedEventArgs const& e) { Wh_Log(L">"); g_autoRevokerList->erase(autoRevokerIt); auto iconView = sender.try_as(); if (!iconView) { return; } auto className = winrt::get_class_name(iconView); Wh_Log(L"className: %s", className.c_str()); auto systemTrayFrameGrid = FindParentByName(iconView, L"SystemTrayFrameGrid"); bool vertical = systemTrayFrameGrid && IsVerticalSystemTray(systemTrayFrameGrid); if (className == L"SystemTray.NotifyIconView") { if (IsChildOfElementByClassName( iconView, L"SystemTray.NotificationAreaOverflow")) { ApplyNotifyIconViewOverflowStyle( iconView, g_settings.overflowIconWidth); } else if (vertical) { ApplyNotifyIconViewStyle( iconView, g_settings.notificationIconWidth, true); ApplyNotifyIconsWrapGridStyleOfIcon( iconView, g_settings.notificationIconWidth); } else { ApplyNotifyIconViewStyle(iconView, g_settings.notificationIconWidth); int rows = g_unloading ? 1 : g_settings.notificationIconRows; if (rows > 1) { ApplyNotifyIconsStackPanelGridStyleOfIcon( iconView, rows, g_settings.notificationIconWidth); } } } else if (vertical) { // Other icons of a vertical tray keep their size. } else if (className == L"SystemTray.IconView") { if (iconView.Name() == L"SystemTrayIcon") { if (IsChildOfElementByName(iconView, L"ControlCenterButton")) { ApplySystemTrayIconStyle( iconView, g_settings.notificationIconWidth); } else if (IsChildOfElementByName(iconView, L"MainStack") || IsChildOfElementByName(iconView, L"NonActivatableStack")) { ApplyNotifyIconViewStyle( iconView, g_settings.notificationIconWidth); } } } else if (className == L"SystemTray.ChevronIconView") { if (IsChildOfElementByName(iconView, L"NotifyIconStack")) { ApplyNotifyIconViewStyle(iconView, g_settings.notificationIconWidth); } } }); return ret; } // The layout in which a vertical tray has a single column of icons, each given // a minimum height whenever the layout is applied. constexpr int kSystemTrayLayoutModeVerticalCompact = 1; using NotifyIconView_ApplyLayoutMode_t = void(WINAPI*)(void* pThis, int layoutMode); NotifyIconView_ApplyLayoutMode_t NotifyIconView_ApplyLayoutMode_Original; void WINAPI NotifyIconView_ApplyLayoutMode_Hook(void* pThis, int layoutMode) { Wh_Log(L"> %d", layoutMode); NotifyIconView_ApplyLayoutMode_Original(pThis, layoutMode); if (g_unloading || layoutMode != kSystemTrayLayoutModeVerticalCompact) { return; } try { FrameworkElement notifyIconView = nullptr; ((IUnknown**)pThis)[1]->QueryInterface( winrt::guid_of(), winrt::put_abi(notifyIconView)); if (!notifyIconView || IsChildOfElementByClassName( notifyIconView, L"SystemTray.NotificationAreaOverflow")) { return; } Wh_Log(L"Setting MinHeight=%d for NotifyIconView", g_settings.notificationIconWidth); notifyIconView.MinHeight(g_settings.notificationIconWidth); // The compact layout state sets its panel some time after the layout of // the icons is updated, replacing the panel set for a grid. The icons // apply their layout mode once they're moved to that panel, and the // grid panel is set again after that. if (g_settings.notificationIconRows <= 1) { return; } auto notificationAreaIcons = FindParentByName(notifyIconView, L"NotificationAreaIcons") .try_as(); if (!notificationAreaIcons || notificationAreaIcons.ItemsPanelRoot() .try_as()) { return; } notificationAreaIcons.Dispatcher().TryRunAsync( winrt::Windows::UI::Core::CoreDispatcherPriority::Normal, [notificationAreaIconsWeak = winrt::make_weak(notificationAreaIcons)]() { auto notificationAreaIcons = notificationAreaIconsWeak.get(); if (!notificationAreaIcons || g_unloading) { return; } try { int rows = g_settings.notificationIconRows; auto systemTrayFrameGrid = FindParentByName( notificationAreaIcons, L"SystemTrayFrameGrid"); if (!systemTrayFrameGrid || !ApplyNotifyIconsCompactLayoutPanel( systemTrayFrameGrid, notificationAreaIcons, rows)) { return; } // Creates the panel, which is styled below. notificationAreaIcons.UpdateLayout(); ApplyNotifyIconsStyle(notificationAreaIcons, rows, g_settings.notificationIconWidth, /*vertical=*/true); } catch (...) { HRESULT hr = winrt::to_hresult(); Wh_Log(L"Error %08X", hr); } }); } catch (...) { HRESULT hr = winrt::to_hresult(); Wh_Log(L"Error %08X", hr); } } // Runs once the layout state is applied, and creates the panel of the icons, // which is set before. Sets the columns of the tray grids after, and schedules // the edge padding of the icons, which is applied after the columns are set. using SystemTrayFrame_UpdateNotificationAreaIconsLayout_t = void(WINAPI*)(void* pThis); SystemTrayFrame_UpdateNotificationAreaIconsLayout_t SystemTrayFrame_UpdateNotificationAreaIconsLayout_Original; void WINAPI SystemTrayFrame_UpdateNotificationAreaIconsLayout_Hook(void* pThis) { Wh_Log(L">"); Controls::ItemsControl notificationAreaIcons = nullptr; if (!g_unloading) { try { FrameworkElement systemTrayFrame = nullptr; ((IUnknown**)pThis)[1]->QueryInterface( winrt::guid_of(), winrt::put_abi(systemTrayFrame)); FrameworkElement systemTrayFrameGrid = nullptr; if (systemTrayFrame) { systemTrayFrameGrid = FindChildByName(systemTrayFrame, L"SystemTrayFrameGrid"); } if (systemTrayFrameGrid) { if (auto child = FindChildByName(systemTrayFrameGrid, L"NotificationAreaIcons")) { notificationAreaIcons = child.try_as(); } } if (notificationAreaIcons) { ApplyNotifyIconsCompactLayoutPanel( systemTrayFrameGrid, notificationAreaIcons, g_settings.notificationIconRows); } } catch (...) { HRESULT hr = winrt::to_hresult(); Wh_Log(L"Error %08X", hr); } } SystemTrayFrame_UpdateNotificationAreaIconsLayout_Original(pThis); if (g_unloading || !notificationAreaIcons) { return; } try { ApplyNotifyIconsWrapGridColumns(notificationAreaIcons, g_settings.notificationIconRows, g_settings.notificationIconWidth); } catch (...) { HRESULT hr = winrt::to_hresult(); Wh_Log(L"Error %08X", hr); } } using SystemTrayFrame_ApplyPositionAwareHorizontalPadding_t = void(WINAPI*)(void* itemsControl, unsigned int itemCount); SystemTrayFrame_ApplyPositionAwareHorizontalPadding_t SystemTrayFrame_ApplyPositionAwareHorizontalPadding_Original; void WINAPI SystemTrayFrame_ApplyPositionAwareHorizontalPadding_Hook( void* itemsControl, unsigned int itemCount) { Wh_Log(L"> %u", itemCount); if (!g_unloading) { try { Controls::ItemsControl itemsControlObject = nullptr; winrt::copy_from_abi(itemsControlObject, *(void**)itemsControl); if (itemsControlObject && itemsControlObject.Name() == L"NotificationAreaIcons" && ApplyNotifyIconsWrapGridEdgePadding(itemsControlObject, itemCount)) { return; } } catch (...) { HRESULT hr = winrt::to_hresult(); Wh_Log(L"Error %08X", hr); } } SystemTrayFrame_ApplyPositionAwareHorizontalPadding_Original(itemsControl, itemCount); } // The compact layout resets the padding of the icons, which are in a single // column. A grid of icons is padded like in the detailed layout instead. using SystemTrayFrame_ResetIconViewLocalPadding_t = void(WINAPI*)(void* itemsControl); SystemTrayFrame_ResetIconViewLocalPadding_t SystemTrayFrame_ResetIconViewLocalPadding_Original; void WINAPI SystemTrayFrame_ResetIconViewLocalPadding_Hook(void* itemsControl) { Wh_Log(L">"); if (!g_unloading && g_settings.notificationIconRows > 1) { try { Controls::ItemsControl itemsControlObject = nullptr; winrt::copy_from_abi(itemsControlObject, *(void**)itemsControl); if (itemsControlObject && itemsControlObject.Name() == L"NotificationAreaIcons" && ApplyNotifyIconsWrapGridEdgePadding( itemsControlObject, itemsControlObject.Items().Size())) { return; } } catch (...) { HRESULT hr = winrt::to_hresult(); Wh_Log(L"Error %08X", hr); } } SystemTrayFrame_ResetIconViewLocalPadding_Original(itemsControl); } void ApplyOverflowStyle(FrameworkElement overflowRootGrid) { Controls::WrapGrid wrapGrid = nullptr; FrameworkElement child = overflowRootGrid; if ((child = FindChildByClassName( child, L"Windows.UI.Xaml.Controls.ItemsControl")) && (child = FindChildByClassName( child, L"Windows.UI.Xaml.Controls.ItemsPresenter")) && (child = FindChildByClassName(child, L"Windows.UI.Xaml.Controls.WrapGrid"))) { wrapGrid = child.try_as(); } if (!wrapGrid) { return; } int width = g_unloading ? 40 : g_settings.overflowIconWidth; int maxRows = g_unloading ? 5 : g_settings.overflowIconsPerRow; Wh_Log( L"Setting ItemWidth/ItemHeight=%d, MaximumRowsOrColumns=%d for " L"WrapGrid", width, maxRows); wrapGrid.ItemWidth(width); wrapGrid.ItemHeight(width); wrapGrid.MaximumRowsOrColumns(maxRows); EnumChildElements(wrapGrid, [width](FrameworkElement child) { auto className = winrt::get_class_name(child); if (className != L"Windows.UI.Xaml.Controls.ContentPresenter") { Wh_Log(L"Unsupported class name %s of child", className.c_str()); return false; } auto notifyIconView = FindChildByClassName(child, L"SystemTray.NotifyIconView"); if (notifyIconView) { ApplyNotifyIconViewOverflowStyle(notifyIconView, width); } return false; }); } using OverflowXamlIslandManager_InitializeIfNeeded_t = void(WINAPI*)(void* pThis); OverflowXamlIslandManager_InitializeIfNeeded_t OverflowXamlIslandManager_InitializeIfNeeded_Original; void WINAPI OverflowXamlIslandManager_InitializeIfNeeded_Hook(void* pThis) { Wh_Log(L">"); OverflowXamlIslandManager_InitializeIfNeeded_Original(pThis); if (g_overflowRootGrid.get()) { return; } FrameworkElement overflowRootGrid = nullptr; ((IUnknown**)pThis)[5]->QueryInterface(winrt::guid_of(), winrt::put_abi(overflowRootGrid)); if (!overflowRootGrid) { Wh_Log(L"No OverflowRootGrid"); return; } if (!overflowRootGrid.IsLoaded()) { Wh_Log(L"OverflowRootGrid not loaded"); return; } g_overflowRootGrid = overflowRootGrid; ApplyOverflowStyle(overflowRootGrid); } using StackViewModel_UpdateIconIndexes_t = void(WINAPI*)(void* pThis); StackViewModel_UpdateIconIndexes_t StackViewModel_UpdateIconIndexes_Original; void WINAPI StackViewModel_UpdateIconIndexes_Hook(void* pThis) { Wh_Log(L">"); StackViewModel_UpdateIconIndexes_Original(pThis); int rows = g_unloading ? 1 : g_settings.notificationIconRows; if (rows > 1) { if (auto stackPanel = g_notificationAreaIconsStackPanel.get()) { ApplyNotifyIconsStackPanelGridStyle( stackPanel, rows, g_settings.notificationIconWidth); } } } void* CTaskBand_ITaskListWndSite_vftable; using CTaskBand_GetTaskbarHost_t = void*(WINAPI*)(void* pThis, void** result); CTaskBand_GetTaskbarHost_t CTaskBand_GetTaskbarHost_Original; void* TaskbarHost_FrameHeight_Original; using std__Ref_count_base__Decref_t = void(WINAPI*)(void* pThis); std__Ref_count_base__Decref_t std__Ref_count_base__Decref_Original; XamlRoot GetTaskbarXamlRoot(HWND hTaskbarWnd) { HWND hTaskSwWnd = (HWND)GetProp(hTaskbarWnd, L"TaskbandHWND"); if (!hTaskSwWnd) { return nullptr; } void* taskBand = (void*)GetWindowLongPtr(hTaskSwWnd, 0); void* taskBandForTaskListWndSite = taskBand; for (int i = 0; *(void**)taskBandForTaskListWndSite != CTaskBand_ITaskListWndSite_vftable; i++) { if (i == 20) { return nullptr; } taskBandForTaskListWndSite = (void**)taskBandForTaskListWndSite + 1; } void* taskbarHostSharedPtr[2]{}; CTaskBand_GetTaskbarHost_Original(taskBandForTaskListWndSite, taskbarHostSharedPtr); if (!taskbarHostSharedPtr[0] && !taskbarHostSharedPtr[1]) { return nullptr; } size_t taskbarElementIUnknownOffset = 0x10; #if defined(_M_X64) { // 48:83EC 28 | sub rsp,28 // 48:83C1 48 | add rcx,48 const BYTE* b = (const BYTE*)TaskbarHost_FrameHeight_Original; if (b[0] == 0x48 && b[1] == 0x83 && b[2] == 0xEC && b[4] == 0x48 && b[5] == 0x83 && b[6] == 0xC1 && b[7] <= 0x7F) { taskbarElementIUnknownOffset = b[7]; } else { Wh_Log(L"Unsupported TaskbarHost::FrameHeight"); } } #elif defined(_M_ARM64) { // 7f2303d5 pacibsp // fd7bbfa9 stp fp, lr, [sp, #-0x10]! // fd030091 mov fp, sp // 080c41f8 ldr x8, [x0, #0x10]! const DWORD* p = (const DWORD*)TaskbarHost_FrameHeight_Original; if (p[0] == 0xD503237F && (p[1] & 0xFFC07FFF) == 0xA9807BFD && p[2] == 0x910003FD && (p[3] & 0xFFF00FE0) == 0xF8400C00) { taskbarElementIUnknownOffset = (p[3] >> 12) & 0xFF; } else { Wh_Log(L"Unsupported TaskbarHost::FrameHeight"); } } #else #error "Unsupported architecture" #endif auto* taskbarElementIUnknown = *(IUnknown**)((BYTE*)taskbarHostSharedPtr[0] + taskbarElementIUnknownOffset); FrameworkElement taskbarElement = nullptr; taskbarElementIUnknown->QueryInterface(winrt::guid_of(), winrt::put_abi(taskbarElement)); auto result = taskbarElement ? taskbarElement.XamlRoot() : nullptr; std__Ref_count_base__Decref_Original(taskbarHostSharedPtr[1]); return result; } using RunFromWindowThreadProc_t = void(WINAPI*)(void* parameter); bool RunFromWindowThread(HWND hWnd, RunFromWindowThreadProc_t proc, void* procParam) { static const UINT runFromWindowThreadRegisteredMsg = RegisterWindowMessage(L"Windhawk_RunFromWindowThread_" WH_MOD_ID); struct RUN_FROM_WINDOW_THREAD_PARAM { RunFromWindowThreadProc_t proc; void* procParam; }; DWORD dwThreadId = GetWindowThreadProcessId(hWnd, nullptr); if (dwThreadId == 0) { return false; } if (dwThreadId == GetCurrentThreadId()) { proc(procParam); return true; } HHOOK hook = SetWindowsHookEx( WH_CALLWNDPROC, [](int nCode, WPARAM wParam, LPARAM lParam) -> LRESULT { if (nCode == HC_ACTION) { const CWPSTRUCT* cwp = (const CWPSTRUCT*)lParam; if (cwp->message == runFromWindowThreadRegisteredMsg) { RUN_FROM_WINDOW_THREAD_PARAM* param = (RUN_FROM_WINDOW_THREAD_PARAM*)cwp->lParam; param->proc(param->procParam); } } return CallNextHookEx(nullptr, nCode, wParam, lParam); }, nullptr, dwThreadId); if (!hook) { return false; } RUN_FROM_WINDOW_THREAD_PARAM param; param.proc = proc; param.procParam = procParam; SendMessage(hWnd, runFromWindowThreadRegisteredMsg, 0, (LPARAM)¶m); UnhookWindowsHookEx(hook); return true; } void LoadSettings() { g_settings.notificationIconWidth = std::max(Wh_GetIntSetting(L"notificationIconWidth"), 1); g_settings.notificationIconRows = std::max(Wh_GetIntSetting(L"notificationIconRows"), 1); PCWSTR gridArrangement = Wh_GetStringSetting(L"gridArrangement"); g_settings.gridArrangement = GridArrangement::rowFirstLeftToRight; if (wcscmp(gridArrangement, L"columnFirstTopToBottom") == 0) { g_settings.gridArrangement = GridArrangement::columnFirstTopToBottom; } else if (wcscmp(gridArrangement, L"rowFirstBottomRowFirst") == 0) { g_settings.gridArrangement = GridArrangement::rowFirstBottomRowFirst; } else if (wcscmp(gridArrangement, L"columnFirstBottomToTop") == 0) { g_settings.gridArrangement = GridArrangement::columnFirstBottomToTop; } else if (wcscmp(gridArrangement, L"columnFirstBottomToTopRightToLeft") == 0) { g_settings.gridArrangement = GridArrangement::columnFirstBottomToTopRightToLeft; } Wh_FreeStringSetting(gridArrangement); g_settings.overflowIconWidth = std::max(Wh_GetIntSetting(L"overflowIconWidth"), 1); g_settings.overflowIconsPerRow = std::max(Wh_GetIntSetting(L"overflowIconsPerRow"), 1); } void ApplySettings() { struct ApplySettingsParam { HWND hTaskbarWnd; int rows; int width; winrt::Windows::UI::Core::CoreDispatcher dispatcher{nullptr}; }; Wh_Log(L"Applying settings"); HWND hTaskbarWnd = FindCurrentProcessTaskbarWnd(); if (!hTaskbarWnd) { Wh_Log(L"No taskbar found"); return; } ApplySettingsParam param{ .hTaskbarWnd = hTaskbarWnd, .rows = g_unloading ? 1 : g_settings.notificationIconRows, .width = g_unloading ? 32 : g_settings.notificationIconWidth, }; RunFromWindowThread( hTaskbarWnd, [](void* pParam) { ApplySettingsParam& param = *(ApplySettingsParam*)pParam; g_autoRevokerList->clear(); auto xamlRoot = GetTaskbarXamlRoot(param.hTaskbarWnd); if (!xamlRoot) { Wh_Log(L"Getting XamlRoot failed"); return; } if (g_unloading) { if (auto content = xamlRoot.Content()) { param.dispatcher = content.Dispatcher(); } } if (!ApplyStyle(xamlRoot, param.rows, param.width)) { Wh_Log(L"ApplyStyle failed"); } if (auto overflowRootGrid = g_overflowRootGrid.get()) { ApplyOverflowStyle(overflowRootGrid); } }, ¶m); // The callbacks queued by NotifyIconView_ApplyLayoutMode_Hook run mod code, // and none are queued while unloading. They run at Normal priority, so all // of them have run once a Low priority callback runs. if (param.dispatcher) { try { param.dispatcher .TryRunAsync( winrt::Windows::UI::Core::CoreDispatcherPriority::Low, [] {}) .get(); } catch (...) { HRESULT hr = winrt::to_hresult(); Wh_Log(L"Error %08X", hr); } } } bool HookSystemTraySymbols(HMODULE module) { // SystemTray.dll, Taskbar.View.dll, ExplorerExtensions.dll WindhawkUtils::SYMBOL_HOOK symbolHooks[] = { { {LR"(public: __cdecl winrt::SystemTray::implementation::IconView::IconView(void))"}, &IconView_IconView_Original, IconView_IconView_Hook, }, { {LR"(private: void __cdecl winrt::SystemTray::OverflowXamlIslandManager::InitializeIfNeeded(void))"}, &OverflowXamlIslandManager_InitializeIfNeeded_Original, OverflowXamlIslandManager_InitializeIfNeeded_Hook, }, { {LR"(private: void __cdecl winrt::SystemTray::implementation::StackViewModel::UpdateIconIndexes(void))"}, &StackViewModel_UpdateIconIndexes_Original, StackViewModel_UpdateIconIndexes_Hook, }, { {LR"(private: void __cdecl winrt::SystemTray::implementation::NotifyIconView::ApplyLayoutMode(enum winrt::SystemTray::SystemTrayLayoutMode))"}, &NotifyIconView_ApplyLayoutMode_Original, NotifyIconView_ApplyLayoutMode_Hook, true, // Only used with the native vertical taskbar. }, { {LR"(private: void __cdecl winrt::SystemTray::implementation::SystemTrayFrame::UpdateNotificationAreaIconsLayout(void))"}, &SystemTrayFrame_UpdateNotificationAreaIconsLayout_Original, SystemTrayFrame_UpdateNotificationAreaIconsLayout_Hook, true, // Only used with the native vertical taskbar. }, { {LR"(private: static void __cdecl winrt::SystemTray::implementation::SystemTrayFrame::ApplyPositionAwareHorizontalPadding(struct winrt::Windows::UI::Xaml::Controls::ItemsControl const &,unsigned int))"}, &SystemTrayFrame_ApplyPositionAwareHorizontalPadding_Original, SystemTrayFrame_ApplyPositionAwareHorizontalPadding_Hook, true, // Only used with the native vertical taskbar. }, { {LR"(private: static void __cdecl winrt::SystemTray::implementation::SystemTrayFrame::ResetIconViewLocalPadding(struct winrt::Windows::UI::Xaml::Controls::ItemsControl const &))"}, &SystemTrayFrame_ResetIconViewLocalPadding_Original, SystemTrayFrame_ResetIconViewLocalPadding_Hook, true, // Only used with the native vertical taskbar. }, }; if (!HookSymbols(module, symbolHooks, ARRAYSIZE(symbolHooks))) { Wh_Log(L"HookSymbols failed"); return false; } return true; } VS_FIXEDFILEINFO* GetModuleVersionInfo(HMODULE hModule, UINT* puPtrLen) { void* pFixedFileInfo = nullptr; UINT uPtrLen = 0; HRSRC hResource = FindResource(hModule, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION); if (hResource) { HGLOBAL hGlobal = LoadResource(hModule, hResource); if (hGlobal) { void* pData = LockResource(hGlobal); if (pData) { if (!VerQueryValue(pData, L"\\", &pFixedFileInfo, &uPtrLen) || uPtrLen == 0) { pFixedFileInfo = nullptr; uPtrLen = 0; } } } } if (puPtrLen) { *puPtrLen = uPtrLen; } return (VS_FIXEDFILEINFO*)pFixedFileInfo; } HMODULE GetSystemTrayModuleHandle() { HMODULE module = GetModuleHandle(L"SystemTray.dll"); if (!module) { module = GetModuleHandle(L"Taskbar.View.dll"); if (module) { // Starting with Taskbar.View.dll 2604.8002.200.6000, the SystemTray // types moved out of Taskbar.View.dll into SystemTray.dll, so don't // hook Taskbar.View.dll at this version and above. VS_FIXEDFILEINFO* fixedFileInfo = GetModuleVersionInfo(module, nullptr); WORD moduleMajor = fixedFileInfo ? HIWORD(fixedFileInfo->dwFileVersionMS) : 0; if (!moduleMajor || moduleMajor >= 2604) { Wh_Log(L"Skipping Taskbar.View.dll version %d", moduleMajor); module = nullptr; } } } if (!module) { module = GetModuleHandle(L"ExplorerExtensions.dll"); } return module; } void HandleLoadedModuleIfSystemTray(HMODULE module, LPCWSTR lpLibFileName) { if (!g_systemTrayModuleHooked && GetSystemTrayModuleHandle() == module && !g_systemTrayModuleHooked.exchange(true)) { Wh_Log(L"Loaded %s", lpLibFileName); if (HookSystemTraySymbols(module)) { Wh_ApplyHookOperations(); } } } using LoadLibraryExW_t = decltype(&LoadLibraryExW); LoadLibraryExW_t LoadLibraryExW_Original; HMODULE WINAPI LoadLibraryExW_Hook(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { HMODULE module = LoadLibraryExW_Original(lpLibFileName, hFile, dwFlags); if (module) { HandleLoadedModuleIfSystemTray(module, lpLibFileName); } return module; } bool HookTaskbarDllSymbols() { HMODULE module = LoadLibraryEx(L"taskbar.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (!module) { Wh_Log(L"Failed to load taskbar.dll"); return false; } WindhawkUtils::SYMBOL_HOOK taskbarDllHooks[] = { { {LR"(const CTaskBand::`vftable'{for `ITaskListWndSite'})"}, &CTaskBand_ITaskListWndSite_vftable, }, { {LR"(public: virtual class std::shared_ptr __cdecl CTaskBand::GetTaskbarHost(void)const )"}, &CTaskBand_GetTaskbarHost_Original, }, { {LR"(public: int __cdecl TaskbarHost::FrameHeight(void)const )"}, &TaskbarHost_FrameHeight_Original, }, { {LR"(public: void __cdecl std::_Ref_count_base::_Decref(void))"}, &std__Ref_count_base__Decref_Original, }, }; return HookSymbols(module, taskbarDllHooks, ARRAYSIZE(taskbarDllHooks)); } BOOL Wh_ModInit() { Wh_Log(L">"); LoadSettings(); if (HMODULE systemTrayModule = GetSystemTrayModuleHandle()) { g_systemTrayModuleHooked = true; if (!HookSystemTraySymbols(systemTrayModule)) { return FALSE; } } else { Wh_Log(L"System tray module not loaded yet"); HMODULE kernelBaseModule = GetModuleHandle(L"kernelbase.dll"); auto pKernelBaseLoadLibraryExW = (decltype(&LoadLibraryExW))GetProcAddress(kernelBaseModule, "LoadLibraryExW"); WindhawkUtils::SetFunctionHook(pKernelBaseLoadLibraryExW, LoadLibraryExW_Hook, &LoadLibraryExW_Original); } if (!HookTaskbarDllSymbols()) { return FALSE; } return TRUE; } void Wh_ModAfterInit() { Wh_Log(L">"); if (!g_systemTrayModuleHooked) { if (HMODULE systemTrayModule = GetSystemTrayModuleHandle()) { if (!g_systemTrayModuleHooked.exchange(true)) { Wh_Log(L"Got system tray module"); if (HookSystemTraySymbols(systemTrayModule)) { Wh_ApplyHookOperations(); } } } } ApplySettings(); } void Wh_ModBeforeUninit() { Wh_Log(L">"); g_unloading = true; ApplySettings(); } void Wh_ModUninit() { Wh_Log(L">"); } void Wh_ModSettingsChanged() { Wh_Log(L">"); LoadSettings(); ApplySettings(); }