如何检查鼠标按钮是否在屏幕上的任何地方按下,甚至在我的主窗口之外?

How to check if mouse button is pressed anywhere on screen , even outside of my mainwindow?

在 Qt 中是否可以检测在我的应用程序内部和外部按下的鼠标按钮 window,我想有一种方法可以检测我的应用程序内部的鼠标点击 window,但是如何检测呢?在主 window 的内部+外部单击 ?


Is it possible to detect mouse buttons pressed inside and outside of my application window in Qt

我不知道 Qt 本身是否提供了这样的功能,但底层 OS 可能提供了。例如,在 Windows 上,您可以通过 SetWindowsHookEx() or RegisterRawInputDevices() 使用鼠标钩子来全局监控鼠标 activity。

我找到了解决方案,我在使用它之前实际上并没有初始化IUIAutomation* automation = NULL;,现在更新版本是

BOOL InitializeUIAutomation(IUIAutomation** automation)
{
    CoInitialize(NULL);
    HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
        CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation),
        (void**)automation);
    return (SUCCEEDED(hr));
}

LRESULT CALLBACK MainWindow::mouseProc(int Code, WPARAM wParam, LPARAM lParam)
{
    //Q_UNUSED(Code);
        auto& ms = *(const MSLLHOOKSTRUCT*)lParam;
        MSLLHOOKSTRUCT* pMouseStruct = (MSLLHOOKSTRUCT*)lParam;
        if (pMouseStruct != nullptr)
        {
            if (wParam == WM_LBUTTONDOWN)
            {
                qDebug() << "Test Example";

                IUIAutomationElement* elem = NULL;
                IUIAutomation* automation = NULL;
                BOOL stet = InitializeUIAutomation(&automation);  //added this 
                POINT mousePt;
                BSTR elemName = NULL;
                if (stet)
                {
                    GetCursorPos(&mousePt);
                    HRESULT hr = automation->ElementFromPoint(mousePt, &elem); //getting unhandles exception in call back

                    if (SUCCEEDED(hr) && elem != NULL)
                    {
                        elem->get_CurrentName(&elemName);
                        std::wstring ws(elemName, SysStringLen(elemName));
                        // std::wcout << ws << std::endl;
                        QString testing = QString::fromStdWString(ws);
                        qDebug() << testing;
                        elem->Release();
                    }
                    automation->Release();

                    SysFreeString(elemName);
                }
            }
            // emit instance().mouseEvent();
        }
    // After that you need to return back to the chain hook event handlers
    return CallNextHookEx(NULL, Code, wParam, lParam);
}

void MainWindow::closeEvent(QCloseEvent* event)  // function executed when window is closed.
{
    // Code for destroy
    CoUninitialize();
}