Files
PowerToys/src/runner/powertoy_module.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

121 lines
4.4 KiB
C++

#include "pch.h"
#include "powertoy_module.h"
#include "centralized_kb_hook.h"
#include "centralized_hotkeys.h"
#include <common/logger/logger.h>
#include <common/utils/winapi_error.h>
std::map<std::wstring, PowertoyModule>& modules()
{
static std::map<std::wstring, PowertoyModule> modules;
return modules;
}
PowertoyModule load_powertoy(const std::wstring_view filename)
{
auto handle = winrt::check_pointer(LoadLibraryW(filename.data()));
auto create = reinterpret_cast<powertoy_create_func>(GetProcAddress(handle, "powertoy_create"));
if (!create)
{
FreeLibrary(handle);
winrt::throw_last_error();
}
auto pt_module = create();
if (!pt_module)
{
FreeLibrary(handle);
winrt::throw_hresult(winrt::hresult(E_POINTER));
}
return PowertoyModule(pt_module, handle);
}
json::JsonObject PowertoyModule::json_config() const
{
int size = 0;
pt_module->get_config(nullptr, &size);
std::wstring result;
result.resize(static_cast<size_t>(size) - 1);
pt_module->get_config(result.data(), &size);
return json::JsonObject::Parse(result);
}
PowertoyModule::PowertoyModule(PowertoyModuleIface* pt_module, HMODULE handle) :
handle(handle), pt_module(pt_module), hkmng(HotkeyConflictDetector::HotkeyConflictManager::GetInstance())
{
if (!pt_module)
{
throw std::runtime_error("Module not initialized");
}
remove_hotkey_records();
update_hotkeys();
UpdateHotkeyEx();
}
void PowertoyModule::update_hotkeys()
{
CentralizedKeyboardHook::ClearModuleHotkeys(pt_module->get_key());
size_t hotkeyCount = pt_module->get_hotkeys(nullptr, 0);
std::vector<PowertoyModuleIface::Hotkey> hotkeys(hotkeyCount);
pt_module->get_hotkeys(hotkeys.data(), hotkeyCount);
auto modulePtr = pt_module.get();
for (size_t i = 0; i < hotkeyCount; i++)
{
if (hotkeys[i].isShown)
{
hkmng.AddHotkey(hotkeys[i], pt_module->get_key(), static_cast<int>(i), pt_module->is_enabled());
CentralizedKeyboardHook::SetHotkeyAction(pt_module->get_key(), hotkeys[i], [modulePtr, i] {
Logger::trace(L"{} hotkey is invoked from Centralized keyboard hook", modulePtr->get_key());
return modulePtr->on_hotkey(i);
});
}
}
}
void PowertoyModule::UpdateHotkeyEx()
{
CentralizedHotkeys::UnregisterHotkeysForModule(pt_module->get_key());
CentralizedKeyboardHook::ClearPressedKeyActions(pt_module->get_key());
auto container = pt_module->GetHotkeyEx();
if (container.has_value() && pt_module->is_enabled())
{
hkmng.RemoveHotkeyByModule(pt_module->get_key());
auto hotkey = container.value();
auto modulePtr = pt_module.get();
auto action = [modulePtr](WORD /*modifiersMask*/, WORD /*vkCode*/) {
Logger::trace(L"{} hotkey Ex is invoked from Centralized keyboard hook", modulePtr->get_key());
modulePtr->OnHotkeyEx();
};
HotkeyConflictDetector::Hotkey _hotkey = HotkeyConflictDetector::ShortcutToHotkey({ hotkey.modifiersMask, hotkey.vkCode });
hkmng.AddHotkey(_hotkey, pt_module->get_key(), 0, pt_module->is_enabled()); // This is the only one activation hotkey, so we use "0" as the name.
CentralizedHotkeys::AddHotkeyAction({ hotkey.modifiersMask, hotkey.vkCode }, { pt_module->get_key(), action });
}
// HACK:
// Just for enabling the shortcut guide legacy behavior of pressing the Windows Key.
// This is not the sort of behavior we'd like to have generalized on other modules.
// But this was a way to bring back the long windows key behavior that the community wanted back while maintaining the separate process.
if (pt_module->is_enabled() && pt_module->keep_track_of_pressed_win_key())
{
auto modulePtr = pt_module.get();
auto action = [modulePtr] {
if (modulePtr->is_enabled())
{
return modulePtr->on_hotkey(PowertoyModuleIface::WIN_KEY_HOLD_HOTKEY_ID);
}
return false;
};
CentralizedKeyboardHook::AddPressedKeyAction(pt_module->get_key(), VK_LWIN, pt_module->milliseconds_win_key_must_be_pressed(), action);
CentralizedKeyboardHook::AddPressedKeyAction(pt_module->get_key(), VK_RWIN, pt_module->milliseconds_win_key_must_be_pressed(), action);
}
}