Compare commits

...

5 Commits

Author SHA1 Message Date
seraphima
6427d0a454 replaced keyboard hook 2024-03-28 14:33:26 +01:00
seraphima
4573865575 replace keyboard hooks (ctrl, shift) 2024-03-28 14:33:26 +01:00
seraphima
aa1f79a2ad handle input 2024-03-28 14:33:25 +01:00
seraphima
c365b5a723 static 2024-03-28 14:33:25 +01:00
seraphima
641c19722d init RawInputDevice 2024-03-28 14:33:25 +01:00
10 changed files with 185 additions and 155 deletions

View File

@@ -32,14 +32,6 @@ FancyZonesApp::~FancyZonesApp()
m_app->Destroy();
m_app = nullptr;
if (s_llKeyboardHook)
{
if (UnhookWindowsHookEx(s_llKeyboardHook))
{
s_llKeyboardHook = nullptr;
}
}
m_staticWinEventHooks.erase(std::remove_if(begin(m_staticWinEventHooks),
end(m_staticWinEventHooks),
[](const HWINEVENTHOOK hook) {
@@ -66,24 +58,6 @@ void FancyZonesApp::Run()
void FancyZonesApp::InitHooks()
{
#if defined(DISABLE_LOWLEVEL_HOOKS_WHEN_DEBUGGED)
const bool hook_disabled = IsDebuggerPresent();
#else
const bool hook_disabled = false;
#endif
if (!hook_disabled)
{
s_llKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle(NULL), NULL);
if (!s_llKeyboardHook)
{
DWORD errorCode = GetLastError();
show_last_error_message(L"SetWindowsHookEx", errorCode, GET_RESOURCE_STRING(IDS_POWERTOYS_FANCYZONES).c_str());
auto errorMessage = get_last_error_message(errorCode);
Trace::FancyZones::Error(errorCode, errorMessage.has_value() ? errorMessage.value() : L"", L"enable.SetWindowsHookEx");
}
}
std::array<DWORD, 6> events_to_subscribe = {
EVENT_SYSTEM_MOVESIZESTART,
EVENT_SYSTEM_MOVESIZEEND,
@@ -174,8 +148,3 @@ void FancyZonesApp::HandleWinHookEvent(WinHookEvent* data) noexcept
break;
}
}
intptr_t FancyZonesApp::HandleKeyboardHookEvent(LowlevelKeyboardEvent* data) noexcept
{
return m_app.as<IFancyZonesCallback>()->OnKeyDown(data->lParam);
}

View File

@@ -14,7 +14,6 @@ public:
private:
static inline FancyZonesApp* s_instance = nullptr;
static inline HHOOK s_llKeyboardHook = nullptr;
winrt::com_ptr<IFancyZones> m_app;
HWINEVENTHOOK m_objectLocationWinEventHook = nullptr;
@@ -25,25 +24,6 @@ private:
void InitHooks();
void HandleWinHookEvent(WinHookEvent* data) noexcept;
intptr_t HandleKeyboardHookEvent(LowlevelKeyboardEvent* data) noexcept;
static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
LowlevelKeyboardEvent event;
if (nCode == HC_ACTION && wParam == WM_KEYDOWN)
{
event.lParam = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
event.wParam = wParam;
if (s_instance)
{
if (s_instance->HandleKeyboardHookEvent(&event) == 1)
{
return 1;
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
static void CALLBACK WinHookProc(HWINEVENTHOOK winEventHook,
DWORD event,

View File

@@ -8,9 +8,6 @@ DraggingState::DraggingState(const std::function<void()>& keyUpdateCallback) :
m_secondaryMouseState(false),
m_middleMouseState(false),
m_mouseHook(std::bind(&DraggingState::OnSecondaryMouseDown, this), std::bind(&DraggingState::OnMiddleMouseDown, this)),
m_leftShiftKeyState(keyUpdateCallback),
m_rightShiftKeyState(keyUpdateCallback),
m_ctrlKeyState(keyUpdateCallback),
m_keyUpdateCallback(keyUpdateCallback)
{
}
@@ -21,50 +18,29 @@ void DraggingState::Enable()
{
m_mouseHook.enable();
}
m_leftShiftKeyState.enable();
m_rightShiftKeyState.enable();
m_ctrlKeyState.enable();
}
void DraggingState::Disable()
{
const bool leftShiftPressed = m_leftShiftKeyState.state();
const bool rightShiftPressed = m_rightShiftKeyState.state();
if (FancyZonesSettings::settings().shiftDrag)
{
if (leftShiftPressed)
{
FancyZonesUtils::SwallowKey(VK_LSHIFT);
}
if (rightShiftPressed)
{
FancyZonesUtils::SwallowKey(VK_RSHIFT);
}
}
m_dragging = false;
m_secondaryMouseState = false;
m_middleMouseState = false;
m_shift = false;
m_ctrl = false;
m_mouseHook.disable();
m_leftShiftKeyState.disable();
m_rightShiftKeyState.disable();
m_ctrlKeyState.disable();
}
void DraggingState::UpdateDraggingState() noexcept
{
// This updates m_dragEnabled depending on if the shift key is being held down
// This updates m_dragging depending on if the shift key is being held down
if (FancyZonesSettings::settings().shiftDrag)
{
m_dragging = ((m_leftShiftKeyState.state() || m_rightShiftKeyState.state()) ^ m_secondaryMouseState);
m_dragging = (m_shift ^ m_secondaryMouseState);
}
else
{
m_dragging = !((m_leftShiftKeyState.state() || m_rightShiftKeyState.state()) ^ m_secondaryMouseState);
m_dragging = !(m_shift ^ m_secondaryMouseState);
}
}
@@ -95,5 +71,17 @@ bool DraggingState::IsDragging() const noexcept
bool DraggingState::IsSelectManyZonesState() const noexcept
{
return m_ctrlKeyState.state() || m_middleMouseState;
}
return m_ctrl || m_middleMouseState;
}
void DraggingState::SetShiftState(bool value) noexcept
{
m_shift = value;
m_keyUpdateCallback();
}
void DraggingState::SetCtrlState(bool value) noexcept
{
m_ctrl = value;
m_keyUpdateCallback();
}

View File

@@ -16,6 +16,9 @@ public:
bool IsDragging() const noexcept;
bool IsSelectManyZonesState() const noexcept;
void SetShiftState(bool value) noexcept;
void SetCtrlState(bool value) noexcept;
private:
void OnSecondaryMouseDown();
void OnMiddleMouseDown();
@@ -23,9 +26,10 @@ private:
std::atomic<bool> m_secondaryMouseState;
std::atomic<bool> m_middleMouseState;
MouseButtonsHook m_mouseHook;
KeyState<VK_LSHIFT> m_leftShiftKeyState;
KeyState<VK_RSHIFT> m_rightShiftKeyState;
KeyState<VK_LCONTROL, VK_RCONTROL> m_ctrlKeyState;
bool m_shift{};
bool m_ctrl{};
std::function<void()> m_keyUpdateCallback;
bool m_dragging{}; // True if we should be showing zone hints while dragging

View File

@@ -21,6 +21,7 @@
#include <FancyZonesLib/FancyZonesWindowProcessing.h>
#include <FancyZonesLib/FancyZonesWindowProperties.h>
#include <FancyZonesLib/FancyZonesWinHookEventIDs.h>
#include <FancyZonesLib/KeyboardInput.h>
#include <FancyZonesLib/MonitorUtils.h>
#include <FancyZonesLib/on_thread_executor.h>
#include <FancyZonesLib/Settings.h>
@@ -132,8 +133,6 @@ public:
IFACEMETHODIMP_(void)
VirtualDesktopChanged() noexcept;
IFACEMETHODIMP_(bool)
OnKeyDown(PKBDLLHOOKSTRUCT info) noexcept;
void MoveSizeStart(HWND window, HMONITOR monitor);
void MoveSizeUpdate(HMONITOR monitor, POINT const& ptScreen);
@@ -143,6 +142,7 @@ public:
void ToggleEditor() noexcept;
LRESULT WndProc(HWND, UINT, WPARAM, LPARAM) noexcept;
void OnKeyboardInput(WPARAM flags, HRAWINPUT hInput) noexcept;
void OnDisplayChange(DisplayChangeType changeType) noexcept;
bool AddWorkArea(HMONITOR monitor, const FancyZonesDataTypes::WorkAreaId& id, const FancyZonesUtils::Rect& rect) noexcept;
@@ -220,7 +220,13 @@ FancyZones::Run() noexcept
m_window = CreateWindowExW(WS_EX_TOOLWINDOW, NonLocalizable::ToolWindowClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, m_hinstance, this);
if (!m_window)
{
Logger::error(L"Failed to create FancyZones window");
Logger::critical(L"Failed to create FancyZones window");
return;
}
if (!KeyboardInput::Initialize(m_window))
{
Logger::critical(L"Failed to register raw input device");
return;
}
@@ -453,64 +459,6 @@ void FancyZones::WindowCreated(HWND window) noexcept
}
}
// IFancyZonesCallback
IFACEMETHODIMP_(bool)
FancyZones::OnKeyDown(PKBDLLHOOKSTRUCT info) noexcept
{
// Return true to swallow the keyboard event
bool const shift = GetAsyncKeyState(VK_SHIFT) & 0x8000;
bool const win = GetAsyncKeyState(VK_LWIN) & 0x8000 || GetAsyncKeyState(VK_RWIN) & 0x8000;
bool const alt = GetAsyncKeyState(VK_MENU) & 0x8000;
bool const ctrl = GetAsyncKeyState(VK_CONTROL) & 0x8000;
if ((win && !shift && !ctrl) || (win && ctrl && alt))
{
if ((info->vkCode == VK_RIGHT) || (info->vkCode == VK_LEFT) || (info->vkCode == VK_UP) || (info->vkCode == VK_DOWN))
{
if (ShouldProcessSnapHotkey(info->vkCode))
{
Trace::FancyZones::OnKeyDown(info->vkCode, win, ctrl, false /*inMoveSize*/);
// Win+Left, Win+Right will cycle through Zones in the active ZoneSet when WM_PRIV_SNAP_HOTKEY's handled
PostMessageW(m_window, WM_PRIV_SNAP_HOTKEY, 0, info->vkCode);
return true;
}
}
}
if (FancyZonesSettings::settings().quickLayoutSwitch)
{
int digitPressed = -1;
if ('0' <= info->vkCode && info->vkCode <= '9')
{
digitPressed = info->vkCode - '0';
}
else if (VK_NUMPAD0 <= info->vkCode && info->vkCode <= VK_NUMPAD9)
{
digitPressed = info->vkCode - VK_NUMPAD0;
}
bool dragging = m_draggingState.IsDragging();
bool changeLayoutWhileNotDragging = !dragging && !shift && win && ctrl && alt && digitPressed != -1;
bool changeLayoutWhileDragging = dragging && digitPressed != -1;
if (changeLayoutWhileNotDragging || changeLayoutWhileDragging)
{
auto layoutId = LayoutHotkeys::instance().GetLayoutId(digitPressed);
if (layoutId.has_value())
{
PostMessageW(m_window, WM_PRIV_QUICK_LAYOUT_KEY, 0, static_cast<LPARAM>(digitPressed));
Trace::FancyZones::QuickLayoutSwitched(changeLayoutWhileNotDragging);
return true;
}
}
}
if (m_draggingState.IsDragging() && shift)
{
return true;
}
return false;
}
void FancyZones::ToggleEditor() noexcept
{
_TRACER_;
@@ -580,6 +528,12 @@ LRESULT FancyZones::WndProc(HWND window, UINT message, WPARAM wparam, LPARAM lpa
}
break;
case WM_INPUT:
{
OnKeyboardInput(wparam, reinterpret_cast<HRAWINPUT>(lparam));
}
break;
case WM_SETTINGCHANGE:
{
if (wparam == SPI_SETWORKAREA)
@@ -717,6 +671,82 @@ LRESULT FancyZones::WndProc(HWND window, UINT message, WPARAM wparam, LPARAM lpa
return 0;
}
void FancyZones::OnKeyboardInput(WPARAM /*flags*/, HRAWINPUT hInput) noexcept
{
auto input = KeyboardInput::OnKeyboardInput(hInput);
if (!input.has_value())
{
return;
}
USHORT key = input.value().vkKey;
switch (key)
{
case VK_SHIFT:
{
m_draggingState.SetShiftState(input.value().pressed);
}
break;
case VK_CONTROL:
{
m_draggingState.SetCtrlState(input.value().pressed);
}
break;
case VK_RIGHT:
case VK_LEFT:
case VK_UP:
case VK_DOWN:
{
bool const win = GetAsyncKeyState(VK_LWIN) & 0x8000 || GetAsyncKeyState(VK_RWIN) & 0x8000;
bool const ctrl = GetAsyncKeyState(VK_CONTROL) & 0x8000;
if (win && ShouldProcessSnapHotkey(key))
{
Trace::FancyZones::OnKeyDown(key, win, ctrl, false /*inMoveSize*/);
// Win+Left, Win+Right will cycle through Zones in the active ZoneSet when WM_PRIV_SNAP_HOTKEY's handled
PostMessageW(m_window, WM_PRIV_SNAP_HOTKEY, 0, key);
}
}
break;
default:
{
if (FancyZonesSettings::settings().quickLayoutSwitch && input.value().pressed)
{
int digitPressed = -1;
if ('0' <= key && key <= '9')
{
digitPressed = key - '0';
}
else if (VK_NUMPAD0 <= key && key <= VK_NUMPAD9)
{
digitPressed = key - VK_NUMPAD0;
}
bool const shift = GetAsyncKeyState(VK_SHIFT) & 0x8000;
bool const win = GetAsyncKeyState(VK_LWIN) & 0x8000 || GetAsyncKeyState(VK_RWIN) & 0x8000;
bool const alt = GetAsyncKeyState(VK_MENU) & 0x8000;
bool const ctrl = GetAsyncKeyState(VK_CONTROL) & 0x8000;
bool dragging = m_draggingState.IsDragging();
bool changeLayoutWhileNotDragging = !dragging && !shift && win && ctrl && alt && digitPressed != -1;
bool changeLayoutWhileDragging = dragging && digitPressed != -1;
if (changeLayoutWhileNotDragging || changeLayoutWhileDragging)
{
auto layoutId = LayoutHotkeys::instance().GetLayoutId(digitPressed);
if (layoutId.has_value())
{
PostMessageW(m_window, WM_PRIV_QUICK_LAYOUT_KEY, 0, static_cast<LPARAM>(digitPressed));
Trace::FancyZones::QuickLayoutSwitched(changeLayoutWhileNotDragging);
}
}
}
}
break;
}
}
void FancyZones::OnDisplayChange(DisplayChangeType changeType) noexcept
{
Logger::info(L"Display changed, type: {}", DisplayChangeTypeName(changeType));

View File

@@ -37,15 +37,6 @@ interface __declspec(uuid("{2CB37E8F-87E6-4AEC-B4B2-E0FDC873343F}")) IFancyZones
*/
IFACEMETHOD_(void, HandleWinHookEvent)
(const WinHookEvent* data) = 0;
/**
* Process keyboard event.
*
* @param info Information about low level keyboard event.
* @returns Boolean indicating if this event should be passed on further to other applications
* in event chain, or should it be suppressed.
*/
IFACEMETHOD_(bool, OnKeyDown)
(PKBDLLHOOKSTRUCT info) = 0;
};
winrt::com_ptr<IFancyZones> MakeFancyZones(HINSTANCE hinstance, std::function<void()> disableCallback) noexcept;

View File

@@ -53,6 +53,7 @@
<ClInclude Include="FancyZonesData.h" />
<ClInclude Include="GuidUtils.h" />
<ClInclude Include="JsonHelpers.h" />
<ClInclude Include="KeyboardInput.h" />
<ClInclude Include="KeyState.h" />
<ClInclude Include="FancyZonesData\LayoutHotkeys.h" />
<ClInclude Include="Layout.h" />
@@ -114,6 +115,7 @@
<ClCompile Include="FancyZonesData\LayoutHotkeys.cpp">
<PrecompiledHeaderFile>../pch.h</PrecompiledHeaderFile>
</ClCompile>
<ClCompile Include="KeyboardInput.cpp" />
<ClCompile Include="Layout.cpp" />
<ClCompile Include="LayoutConfigurator.cpp" />
<ClCompile Include="LayoutAssignedWindows.cpp" />

View File

@@ -168,6 +168,9 @@
<ClInclude Include="FancyZonesData\LastUsedVirtualDesktop.h">
<Filter>Header Files\FancyZonesData</Filter>
</ClInclude>
<ClInclude Include="KeyboardInput.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="pch.cpp">
@@ -278,6 +281,9 @@
<ClCompile Include="FancyZonesWindowProcessing.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="KeyboardInput.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />

View File

@@ -0,0 +1,43 @@
#include "pch.h"
#include "KeyboardInput.h"
#include <hidusage.h>
#include <common/logger/logger.h>
#include <common/utils/winapi_error.h>
bool KeyboardInput::Initialize(HWND window)
{
RAWINPUTDEVICE inputDevice{};
inputDevice.usUsagePage = HID_USAGE_PAGE_GENERIC;
inputDevice.usUsage = HID_USAGE_GENERIC_KEYBOARD;
inputDevice.dwFlags = RIDEV_INPUTSINK;
inputDevice.hwndTarget = window;
bool res = RegisterRawInputDevices(&inputDevice, 1, sizeof(inputDevice));
if (!res)
{
Logger::error(L"RegisterRawInputDevices error: {}", get_last_error_or_default(GetLastError()));
}
return res;
}
std::optional<KeyboardInput::Key> KeyboardInput::OnKeyboardInput(HRAWINPUT hInput)
{
RAWINPUT input;
UINT size = sizeof(input);
auto result = GetRawInputData(hInput, RID_INPUT, &input, &size, sizeof(RAWINPUTHEADER));
if (result < sizeof(RAWINPUTHEADER))
{
return std::nullopt;
}
if (input.header.dwType == RIM_TYPEKEYBOARD)
{
bool pressed = (input.data.keyboard.Flags & RI_KEY_BREAK) == 0;
return KeyboardInput::Key{ input.data.keyboard.VKey, pressed };
}
return std::nullopt;
}

View File

@@ -0,0 +1,17 @@
#pragma once
class KeyboardInput
{
public:
struct Key
{
USHORT vkKey{};
bool pressed{};
};
KeyboardInput() = default;
~KeyboardInput() = default;
static bool Initialize(HWND window);
static std::optional<Key> OnKeyboardInput(HRAWINPUT hInput);
};