Files
PowerToys/src/runner/centralized_hotkeys.cpp
Boliang Zhang ab1f521067 fix(shortcutguide): separate hotkey and Win hold activation (#50000)
## Summary of the Pull Request

Fixes a regression where `Win+Shift+/` was treated as a Windows-key hold
because both activation paths signaled the same event. Regular
activation now opens the full Shortcut Guide independently of the **Hold
Windows key** setting and remains visible after Win is released.

## PR Checklist

- [x] Closes: #49990
- [ ] **Communication:** Core contributor review is still required
- [x] **Tests:** Added/updated and all pass
- [x] **Localization:** N/A - no end-user-facing strings changed
- [x] **Dev docs:** N/A - no developer-facing contract or workflow
changed

## Detailed Description of the Pull Request / Additional comments

- Keeps regular activation on `OnHotkeyEx()` and routes Win-only holds
through the existing `on_hotkey(size_t)` module seam with a reserved ID.
- Adds a dedicated named event for Win-key hold activation while
preserving the existing regular trigger event and module ABI layout.
- Removes `GetAsyncKeyState` trigger-source inference from Shortcut
Guide UI.
- Tracks the source and visible surface explicitly so Win release closes
only hold-owned UI:
- regular hotkey always opens the full guide and is unaffected by hold
settings;
  - **Off** ignores Win-only holds;
  - **Taskbar indicators** closes on Win release;
- **Open Shortcut Guide** follows the configured close-on-release value.
- Handles both left and right Windows keys.
- Clears stale held-key registrations and pending timers before
re-registering them.
- Uses `MOD_NOREPEAT` for centralized activation hotkeys so a held chord
cannot repeatedly toggle the overlay.
- Normalizes `MOD_NOREPEAT` before centralized action lookup, validates
queued hold activations against the current Win-key state, and transfers
hold-owned full-guide surfaces to regular-hotkey ownership.
- Adds a pure activation policy and a data-driven unit-test matrix.

Touched areas:

- `src/runner/` - source-specific dispatch, held-key registration
cleanup, and repeat suppression.
- `src/common/interop/` - additive hold-event constant and WinRT
projection.
- `src/modules/ShortcutGuide/ShortcutGuideModuleInterface/` - dedicated
hold event signaling and hold-setting guard.
- `src/modules/ShortcutGuide/ShortcutGuide.Ui/` - explicit activation
routing and source-aware release behavior.
- `src/modules/ShortcutGuide/ShortcutGuide.UnitTests/` - activation and
release policy coverage.

**Risks and mitigations**

- The existing regular event and settings JSON remain unchanged.
- No virtual method or data member was added to `PowertoyModuleIface`;
the existing `on_hotkey(size_t)` method is reused.
- Duplicate hold callbacks are prevented during settings refresh, and
duplicate hold events are UI no-ops.
- No new telemetry or user-content logging was added.

## Validation Steps Performed

- Built the full x64 Release solution and confirmed the complete payload
starts without missing-module dialogs or Runner startup errors.
- After rebasing onto current `main`, reran
`tools\build\build-essentials.cmd -Platform x64 -Configuration Release`
and built the affected interop, Runner, module-interface,
index-generator, UI, and unit-test projects; all error logs were empty.
- Ran the x64 Release `ShortcutGuide.UnitTests.dll` with
`vstest.console.exe`: **43/43 passed**, including all 15
activation-policy cases.
- After addressing review feedback, rebuilt the x64 Release Runner,
Shortcut Guide UI, and unit-test projects; all builds passed and the
unit tests remained **43/43**.
- Signaled a queued hold after Win was released and confirmed no overlay
opened. Then exercised hold-owned full-guide to regular-hotkey ownership
transfer and confirmed both activations resolved to `ShowFullGuide` and
the guide remained visible after Win release.
- Held an injected `Win+Shift+/` chord for 1.4 seconds over Notepad: the
full guide opened, remained visible after Win release, and logs recorded
two regular activations (open/close) with **zero** hold activations.
- Triggered the dedicated hold event over Notepad in both hold modes:
- **Taskbar indicators:** the 2048x1104 overlay was visible and
`WS_EX_TOPMOST`.
- **Open Shortcut Guide:** the full guide and taskbar indicators were
visible in the same topmost overlay.

Manual verification matrix for a preview build:

1. Set **Hold Windows key** to Off, Taskbar indicators, and Open
Shortcut Guide.
2. In each mode, press and release `Win+Shift+/`; confirm one full panel
remains visible.
3. Hold LWin and RWin separately; confirm only the selected hold
behavior runs.
4. For Open Shortcut Guide, verify close-on-release enabled and
disabled.
5. Verify a second regular activation toggles the full panel closed.

For physical Win-hold checks, run PowerToys at the same or higher
integrity level as the foreground app. `RegisterHotKey` activation can
work across an elevation mismatch while Runner's low-level hold hook
cannot observe the key.

Closes #49990

---------

Copilot-Session: 8271bded-18e8-474e-8e3b-addd71f67f50
2026-08-19 08:11:11 +00:00

124 lines
3.5 KiB
C++

#include "pch.h"
#include "centralized_hotkeys.h"
#include <map>
#include <common/logger/logger.h>
#include <common/utils/winapi_error.h>
#include <common/SettingsAPI/settings_objects.h>
namespace CentralizedHotkeys
{
std::map<Shortcut, std::vector<Action>> actions;
std::map<Shortcut, int> ids;
HWND runnerWindow;
std::wstring ToWstring(const Shortcut& shortcut)
{
std::wstring res = L"";
if (shortcut.modifiersMask & MOD_SHIFT)
{
res += L"shift+";
}
if (shortcut.modifiersMask & MOD_CONTROL)
{
res += L"ctrl+";
}
if (shortcut.modifiersMask & MOD_WIN)
{
res += L"win+";
}
if (shortcut.modifiersMask & MOD_ALT)
{
res += L"alt+";
}
res += PowerToysSettings::HotkeyObject::key_from_code(shortcut.vkCode);
return res;
}
bool AddHotkeyAction(Shortcut shortcut, Action action)
{
if (!actions[shortcut].empty())
{
// It will only work if previous one is rewritten
Logger::warn(L"{} shortcut is already registered", ToWstring(shortcut));
}
actions[shortcut].push_back(action);
// Register hotkey if it is the first shortcut
if (actions[shortcut].size() == 1)
{
if (ids.find(shortcut) == ids.end())
{
static int nextId = 0;
ids[shortcut] = nextId++;
}
if (!RegisterHotKey(runnerWindow, ids[shortcut], shortcut.modifiersMask | MOD_NOREPEAT, shortcut.vkCode))
{
Logger::warn(L"Failed to add {} shortcut. {}", ToWstring(shortcut), get_last_error_or_default(GetLastError()));
return false;
}
Logger::trace(L"{} shortcut registered", ToWstring(shortcut));
return true;
}
return true;
}
void UnregisterHotkeysForModule(std::wstring moduleName)
{
for (auto it = actions.begin(); it != actions.end(); it++)
{
auto val = std::find_if(it->second.begin(), it->second.end(), [moduleName](Action a) { return a.moduleName == moduleName; });
if (val != it->second.end())
{
it->second.erase(val);
if (it->second.empty())
{
if (!UnregisterHotKey(runnerWindow, ids[it->first]))
{
Logger::warn(L"Failed to unregister {} shortcut. {}", ToWstring(it->first), get_last_error_or_default(GetLastError()));
}
else
{
Logger::trace(L"{} shortcut unregistered", ToWstring(it->first));
}
}
}
}
}
void PopulateHotkey(Shortcut shortcut)
{
shortcut.modifiersMask &= static_cast<WORD>(~MOD_NOREPEAT);
const auto actionIt = actions.find(shortcut);
if (actionIt != actions.end() && !actionIt->second.empty())
{
try
{
actionIt->second.begin()->action(shortcut.modifiersMask, shortcut.vkCode);
}
catch(std::exception& ex)
{
Logger::error("Failed to execute hotkey's action. {}", ex.what());
}
catch(...)
{
Logger::error(L"Failed to execute hotkey's action");
}
}
}
void RegisterWindow(HWND hwnd)
{
runnerWindow = hwnd;
}
}