Search code examples
qtmouseeventmouse-hook

QT global mouse listener


I'm new to QT from Java. Is there something like this: https://code.google.com/p/jnativehook/ for QT? Can I get all the mouse events with coordinates? I've done the following:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonRelease)
    {
      QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
      ui->listWidget->addItem(QString("Mouse pressed: %1,%2").arg(mouseEvent>pos().x()).arg(mouseEvent->pos().y()));
    }
  return false;
}

This works fine but it only does it inside my Application and not system wide. What can I do to get this working in QT? Also this only needs to run on windows...


Solution

  • It's actually very simple. I did not find ANY examples or anything.

    I then found a video on YouTube which shows exactly what I'm searching for (For the keyboard but the mouse is basically the same).

    So if ever someone needs this here you go:

    #include <Windows.h>
    #pragma comment(lib, "user32.lib")
    HHOOK hHook = NULL;
    using namespace std;
    
    LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {   
        switch( wParam )
        {
          case WM_LBUTTONDOWN:  qDebug() << "Left click"; // Left click
        }
        return CallNextHookEx(hHook, nCode, wParam, lParam);
    }
    
    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    hHook = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, NULL, 0);
    if (hHook == NULL) {
        qDebug() << "Hook failed";
    }
    ui->setupUi(this);
    }
    

    The following codes can be used inside the switch to detect which event was received:

    • WM_MOUSEMOVE = 0x200
    • WM_LBUTTONDOWN = 0x201
    • WM_LBUTTONUP = 0x202
    • WM_LBUTTONDBLCLK = 0x203
    • WM_RBUTTONDOWN = 0x204
    • WM_RBUTTONUP = 0x205
    • WM_RBUTTONDBLCLK = 0x206
    • WM_MBUTTONDOWN = 0x207
    • WM_MBUTTONUP = 0x208
    • WM_MBUTTONDBLCLK = 0x209
    • WM_MOUSEWHEEL = 0x20A
    • WM_XBUTTONDOWN = 0x20B
    • WM_XBUTTONUP = 0x20C
    • WM_XBUTTONDBLCLK = 0x20D
    • WM_MOUSEHWHEEL = 0x20E