如何检查是否在屏幕的任何位置甚至在主窗口之外都按下了鼠标键?

问题描述

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


解决方法

是否可以检测在Qt中我的应用程序窗口内部和外部按下的鼠标按钮

我不知道Qt本身是否提供这种功能,但是底层操作系统可能会提供。例如,在Windows上,您可以通过SetWindowsHookEx()RegisterRawInputDevices()使用鼠标挂钩来全局监视鼠标活动。

,

我找到了解决方案,在使用之前我并没有初始化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();
}