-1
void MainWindow::mousePressEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
    {
      timer->start(timer_time);
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
    {
        timer->stop();
    }
}

This code works when i use it inside my appliacation, but if I want use it outside it won't be working. How can I do this? It should start timer when LeftButton is pressed and stop when LeftButton release.


SOLUTION: understanding-the-low-level-mouse-and-keyboard-hook-win32


1 Answers1

1

It sounds like hooks are what you're looking for.

Basically, hooks let you interact with the activity within your system, and can be used alter its behavior.

The event listeners in your code will only catch the mouse events that your OS delegates to your QT application. This is why your code only works when you use it inside your application. Using hooks, you can intercept mouse events at a system level and have them handled them in your app instead of letting the OS decide where they should be handled.

Here's what to use to set them up, and here's a little guide on the implementation details.

MatTheWhale
  • 967
  • 6
  • 16
  • Okey, I get it, but now: Can I delete this hook? If my chechbox is cheched I want to capture mouse, but if is unchecked i want switch it off. – Jeremy Clarkson Jul 14 '17 at 14:08
  • Absolutely, there's another function called `UnhookWindowsHookEx` that does exactly that. The documentation for that function should be reachable from the MSDN link I provided. Keep in mind, however, that I have personally encountered issues where hooks would abruptly and silently unhook themselves during a state of extremely high CPU usage. Just something to keep in mind if you ever come across a bug where your hooks randomly stop working. – MatTheWhale Jul 14 '17 at 20:40