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

322 lines
11 KiB
C++

#include "pch.h"
#include "centralized_kb_hook.h"
#include <atomic>
#include <common/debug_control.h>
#include <common/utils/winapi_error.h>
#include <common/logger/logger.h>
#include <common/interop/shared_constants.h>
namespace CentralizedKeyboardHook
{
struct HotkeyDescriptor
{
Hotkey hotkey;
std::wstring moduleName;
std::function<bool()> action;
bool operator<(const HotkeyDescriptor& other) const
{
return hotkey < other.hotkey;
};
};
std::multiset<HotkeyDescriptor> hotkeyDescriptors;
std::mutex mutex;
HHOOK hHook{};
// To store information about handling pressed keys.
struct PressedKeyDescriptor
{
DWORD virtualKey; // Virtual Key code of the key we're keeping track of.
std::wstring moduleName;
std::function<bool()> action;
UINT_PTR idTimer; // Timer ID for calling SET_TIMER with.
UINT millisecondsToPress; // How much time the key must be pressed.
bool operator<(const PressedKeyDescriptor& other) const
{
// We'll use the virtual key as the real key, since looking for a hit with the key is done in the more time sensitive path (low level keyboard hook).
return virtualKey < other.virtualKey;
};
};
std::multiset<PressedKeyDescriptor> pressedKeyDescriptors;
std::mutex pressedKeyMutex;
// keep track of last pressed key, to detect repeated keys and if there are more keys pressed.
const DWORD VK_DISABLED = CommonSharedConstants::VK_DISABLED;
std::atomic<DWORD> vkCodePressed{ VK_DISABLED };
// Save the runner window handle for registering timers.
HWND runnerWindow;
struct DestroyOnExit
{
~DestroyOnExit()
{
Stop();
}
} destroyOnExitObj;
// Handle the pressed key proc
void PressedKeyTimerProc(
HWND hwnd,
UINT /*message*/,
UINT_PTR idTimer,
DWORD /*dwTime*/)
{
std::multiset<PressedKeyDescriptor> copy;
{
// Make a copy, to look for the action to call.
std::unique_lock lock{ pressedKeyMutex };
copy = pressedKeyDescriptors;
}
for (const auto& it : copy)
{
if (it.idTimer == idTimer)
{
// Revalidate that the key is still physically held before firing.
// This prevents ghost activations after the key was already released.
if (GetAsyncKeyState(static_cast<int>(it.virtualKey)) & 0x8000)
{
it.action();
}
}
}
KillTimer(hwnd, idTimer);
}
LRESULT CALLBACK KeyboardHookProc(_In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
const auto& keyPressInfo = *reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
if (keyPressInfo.dwExtraInfo == PowertoyModuleIface::CENTRALIZED_KEYBOARD_HOOK_DONT_TRIGGER_FLAG)
{
// The new keystroke was generated from one of our actions. We should pass it along.
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
// Check if the keys are pressed.
if (!pressedKeyDescriptors.empty())
{
bool wasKeyPressed = vkCodePressed != VK_DISABLED;
// Hold the lock for the shortest possible duration
if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
if (!wasKeyPressed)
{
// If no key was pressed before, let's start a timer to take into account this new key.
std::unique_lock lock{ pressedKeyMutex };
PressedKeyDescriptor dummy{ .virtualKey = keyPressInfo.vkCode };
auto [it, last] = pressedKeyDescriptors.equal_range(dummy);
for (; it != last; ++it)
{
SetTimer(runnerWindow, it->idTimer, it->millisecondsToPress, PressedKeyTimerProc);
}
}
else if (vkCodePressed != keyPressInfo.vkCode)
{
// If a different key was pressed, let's clear the timers we have started for the previous key.
std::unique_lock lock{ pressedKeyMutex };
PressedKeyDescriptor dummy{ .virtualKey = vkCodePressed };
auto [it, last] = pressedKeyDescriptors.equal_range(dummy);
for (; it != last; ++it)
{
KillTimer(runnerWindow, it->idTimer);
}
}
vkCodePressed = keyPressInfo.vkCode;
}
if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)
{
std::unique_lock lock{ pressedKeyMutex };
PressedKeyDescriptor dummy{ .virtualKey = keyPressInfo.vkCode };
auto [it, last] = pressedKeyDescriptors.equal_range(dummy);
for (; it != last; ++it)
{
KillTimer(runnerWindow, it->idTimer);
}
vkCodePressed = 0x100;
}
}
if ((wParam != WM_KEYDOWN) && (wParam != WM_SYSKEYDOWN))
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
Hotkey hotkey{
.win = (GetAsyncKeyState(VK_LWIN) & 0x8000) || (GetAsyncKeyState(VK_RWIN) & 0x8000),
.ctrl = static_cast<bool>(GetAsyncKeyState(VK_CONTROL) & 0x8000),
.shift = static_cast<bool>(GetAsyncKeyState(VK_SHIFT) & 0x8000),
.alt = static_cast<bool>(GetAsyncKeyState(VK_MENU) & 0x8000),
.key = static_cast<unsigned char>(keyPressInfo.vkCode)
};
if (hotkey == Hotkey{})
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
std::function<bool()> action;
{
// Hold the lock for the shortest possible duration
std::unique_lock lock{ mutex };
HotkeyDescriptor dummy{ .hotkey = hotkey };
auto it = hotkeyDescriptors.find(dummy);
if (it != hotkeyDescriptors.end())
{
action = it->action;
}
}
if (action)
{
if (action())
{
// After invoking the hotkey send a dummy key to prevent Start Menu from activating
INPUT dummyEvent[1] = {};
dummyEvent[0].type = INPUT_KEYBOARD;
dummyEvent[0].ki.wVk = 0xFF;
dummyEvent[0].ki.dwFlags = KEYEVENTF_KEYUP;
dummyEvent[0].ki.dwExtraInfo = PowertoyModuleIface::CENTRALIZED_KEYBOARD_HOOK_DONT_TRIGGER_FLAG;
SendInput(1, dummyEvent, sizeof(INPUT));
// Swallow the key press
return 1;
}
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
void SetHotkeyAction(const std::wstring& moduleName, const Hotkey& hotkey, std::function<bool()>&& action) noexcept
{
Logger::trace(L"Register hotkey action for {}", moduleName);
std::unique_lock lock{ mutex };
hotkeyDescriptors.insert({ .hotkey = hotkey, .moduleName = moduleName, .action = std::move(action) });
}
void AddPressedKeyAction(const std::wstring& moduleName, const DWORD vk, const UINT milliseconds, std::function<bool()>&& action) noexcept
{
// Calculate a unique TimerID.
auto hash = std::hash<std::wstring>{}(moduleName); // Hash the module as the upper part of the timer ID.
const UINT upperId = hash & 0xFFFF;
const UINT lowerId = vk & 0xFFFF; // The key to press can be the lower ID.
const UINT timerId = upperId << 16 | lowerId;
std::unique_lock lock{ pressedKeyMutex };
pressedKeyDescriptors.insert({ .virtualKey = vk, .moduleName = moduleName, .action = std::move(action), .idTimer = timerId, .millisecondsToPress = milliseconds });
}
void ClearPressedKeyActions(const std::wstring& moduleName) noexcept
{
Logger::trace(L"UnRegister pressed key action for {}", moduleName);
std::unique_lock lock{ pressedKeyMutex };
const DWORD trackedKey = vkCodePressed.load();
bool removedTrackedKey = false;
auto it = pressedKeyDescriptors.begin();
while (it != pressedKeyDescriptors.end())
{
if (it->moduleName == moduleName)
{
removedTrackedKey |= it->virtualKey == trackedKey;
if (it->idTimer != 0)
{
KillTimer(runnerWindow, it->idTimer);
}
it = pressedKeyDescriptors.erase(it);
}
else
{
++it;
}
}
if (pressedKeyDescriptors.empty())
{
vkCodePressed = VK_DISABLED;
}
else if (removedTrackedKey)
{
PressedKeyDescriptor trackedKeyDescriptor{ .virtualKey = trackedKey };
const auto [first, last] = pressedKeyDescriptors.equal_range(trackedKeyDescriptor);
if (first == last)
{
vkCodePressed = VK_DISABLED;
}
}
}
void ClearModuleHotkeys(const std::wstring& moduleName) noexcept
{
Logger::trace(L"UnRegister hotkey action for {}", moduleName);
{
std::unique_lock lock{ mutex };
auto it = hotkeyDescriptors.begin();
while (it != hotkeyDescriptors.end())
{
if (it->moduleName == moduleName)
{
it = hotkeyDescriptors.erase(it);
}
else
{
++it;
}
}
}
ClearPressedKeyActions(moduleName);
}
void Start() noexcept
{
#if defined(DISABLE_LOWLEVEL_HOOKS_WHEN_DEBUGGED)
const bool hook_disabled = IsDebuggerPresent();
#else
const bool hook_disabled = false;
#endif
if (!hook_disabled)
{
if (!hHook)
{
hHook = SetWindowsHookExW(WH_KEYBOARD_LL, KeyboardHookProc, NULL, NULL);
if (!hHook)
{
DWORD errorCode = GetLastError();
show_last_error_message(L"SetWindowsHookEx", errorCode, L"centralized_kb_hook");
}
}
}
}
void Stop() noexcept
{
// Kill all pending pressed-key timers before unhooking to prevent
// ghost callbacks firing after the hook is removed.
{
std::unique_lock lock{ pressedKeyMutex };
for (const auto& it : pressedKeyDescriptors)
{
KillTimer(runnerWindow, it.idTimer);
}
}
vkCodePressed = VK_DISABLED;
if (hHook && UnhookWindowsHookEx(hHook))
{
hHook = NULL;
}
}
void RegisterWindow(HWND hwnd) noexcept
{
runnerWindow = hwnd;
}
}