简体   繁体   English

在捕获鼠标但窗口未聚焦的同时捕获键盘事件(Win32)

[英]Capture keyboard events while mouse is captured but window not focused (Win32)

I'm implementing a custom control that can initiate drag events. 我正在实现一个可以启动拖动事件的自定义控件。 I initiate a drag when the user presses the left mouse button by processing WM_LBUTTONDOWN and calling SetCapture() . 当用户通过处理WM_LBUTTONDOWN并调用SetCapture()按下鼠标左键时,将启动拖动。 This causes all mouse events, even those outside my control's client area, to be sent to it, exactly as I want. 这将导致所有鼠标事件(甚至是我控件的客户区域之外的鼠标事件)都完全按照我的意愿发送给它。

I would also like to be able to capture key presses so I can cancel the drag if the user presses the ESC key ( VK_ESCAPE ). 我还希望能够捕获按键,因此如果用户按下ESC键( VK_ESCAPE ),则可以取消拖动。 Since my control doesn't have the keyboard focus (and I don't want it to steal the focus away from the control that has it), I can't listen to WM_KEYDOWN . 由于我的控件没有键盘焦点(并且我不希望它从拥有它的控件上夺走焦点),所以我WM_KEYDOWN For other reasons too complicated to explain, I also would prefer not to use the DragDetect() function. 由于其他原因太复杂,难以解释,我也希望不要使用DragDetect()函数。

How can my control find out about ESC key presses while the drag is ongoing? 在拖动过程中,控件如何找到有关ESC按键的信息?

It turns out it's this easy: 事实证明,这很简单:

// message loop...
switch (msg)
{
    // ...

    case WM_LBUTTONDOWN:
        // do some stuff
        RegisterHotKey(hwnd, 0 /* id */, 0, VK_ESCAPE);
        // do some more stuff
        break;

    // ... 

    case WM_HOTKEY:
        if (VK_ESCAPE == HIWORD(lParam) &&
            IDHOT_SNAPDESKTOP != wParam &&
            IDHOT_SNAPWINDOW != wParam)
            {
            // handle ESC keypress
            UnregisterHotKey(hwnd, 0 /* id */);
            }
        break;

    // ...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM