3

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...

user754730
  • 1,341
  • 5
  • 31
  • 62

1 Answers1

5

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
user754730
  • 1,341
  • 5
  • 31
  • 62
  • 5
    You marked your own answer as "accepted", but the answer doesn't answer your own question. Your question was about a global mouse hook using Qt. Your answer was about a global mouse hook using Win32 (an entirely different technology). – Jamin Grey Dec 18 '14 at 21:06
  • This is very helpful! Do you still have the YouTube link? – Jake W Aug 07 '15 at 05:14
  • @JakeW Sorry forgot to add the link... https://www.youtube.com/watch?v=O0C4V6JmlNw There you go... – user754730 Aug 10 '15 at 12:49
  • this is only work on windows. any other platform ? – xiaoyifang Jan 30 '22 at 08:58
  • This does work, but it makes the mouse cursor stutter when loading/deloading the application. Seems to much of a tradeoff to me. – i know nothing Jan 04 '23 at 08:03