Evgenii Legotckoi
June 13, 2016, 11:35 p.m.

Qt WinAPI - Lesson 009. SetWindowsHookEx - Logging mouse events via WinAPI

Functional WinAPI allows by using hooks to monitor system events, such as mouse movement and clicks. This functionality based on callback functions, so if you want to use the Qt system of signaling and slots , you will need to pass one of the methods as a callback to a function for registering callback on a Windows system. But the method must be static, so you need to develop the class as a Singleton.

SetWindowsHookEx

This function is used to register an event handler in the chain hook-handlers to monitor certain events in Windows

  1. HHOOK WINAPI SetWindowsHookEx(
  2. _In_ int       idHook,
  3. _In_ HOOKPROC  lpfn,
  4. _In_ HINSTANCE hMod,
  5. _In_ DWORD     dwThreadId
  6. );

Parameters

idHook [in]

Type: int

The type of hook procedure to be installed. This parameter can be one of the following values.

  • WH_CALLWNDPROC - Installs a hook procedure that monitors messages before the system sends them to the destination window procedure.
  • WH_CALLWNDPROCRET - Installs a hook procedure that monitors messages after they have been processed by the destination window procedure.
  • WH_CBT - Installs a hook procedure that receives notifications useful to a CBT application.
  • WH_DEBUG - Installs a hook procedure useful for debugging other hook procedures.
  • WH_FOREGROUNDIDLE - Installs a hook procedure that will be called when the application's foreground thread is about to become idle. This hook is useful for performing low priority tasks during idle time.
  • WH_GETMESSAGE -Installs a hook procedure that monitors messages posted to a message queue.
  • WH_JOURNALPLAYBACK - Installs a hook procedure that posts messages previously recorded by a WH_JOURNALRECORD hook procedure.
  • WH_JOURNALRECORD - Installs a hook procedure that records input messages posted to the system message queue. This hook is useful for recording macros.
  • WH_KEYBOARD - Installs a hook procedure that monitors keystroke messages.
  • WH_KEYBOARD_LL - Installs a hook procedure that monitors low-level keyboard input events.
  • WH_MOUSE - Installs a hook procedure that monitors mouse messages.
  • WH_MOUSE_LL - Installs a hook procedure that monitors low-level mouse input events.
  • WH_MSGFILTER - Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar.
  • WH_SHELL - Installs a hook procedure that receives notifications useful to shell applications.
  • WH_SYSMSGFILTER - Installs a hook procedure that monitors messages generated as a result of an input event in a dialog box, message box, menu, or scroll bar. The hook procedure monitors these messages for all applications in the same desktop as the calling thread.

lpfn [in]

Type: HOOKPROC

A pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, the lpfn parameter must point to a hook procedure in a DLL. Otherwise, lpfn can point to a hook procedure in the code associated with the current process.

hMod [in]

Type: HINSTANCE

A handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.

dwThreadId [in]

Type: DWORD

The identifier of the thread with which the hook procedure is to be associated. For desktop apps, if this parameter is zero, the hook procedure is associated with all existing threads running in the same desktop as the calling thread. For Windows Store apps, see the Remarks section.

Return value

Type: *HHOOK *

If the function succeeds, the return value is the handle to the hook procedure. If the function fails, the return value is NULL . To get extended error information, call GetLastError .

Project Structure

After a brief introduction to the feature you will use to set the hook, look at the structure of the project, which will demonstrate the connectivity option function to tracking the mouse.

  • MouseHook.pro - project profile;
  • main.cpp - file with main function;
  • mouselogger.h - header file of class for mouse event logging;
  • mouselogger.cpp - source file of class for mouse event logging.

MouseHook.pro

  1. QT += core
  2. QT -= gui
  3.  
  4. CONFIG += c++11
  5.  
  6. TARGET = MouseHook
  7. CONFIG += console
  8. CONFIG -= app_bundle
  9.  
  10. TEMPLATE = app
  11.  
  12. SOURCES += main.cpp \
  13. mouselogger.cpp
  14.  
  15. HEADERS += \
  16. mouselogger.h

main.cpp

In this file, to demonstrate the operation of signals and slots, shows the connection of the lambda functions to the object for logging mouse events, but applied to the connection object using the pattern "Singleton".

  1. #include <QCoreApplication>
  2. #include <QDebug>
  3. #include "mouselogger.h"
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7. QCoreApplication a(argc, argv);
  8.  
  9. QObject::connect(&MouseLogger::instance(), &MouseLogger::mouseEvent,
  10. [](){
  11. qDebug() << "Mouse Event";
  12. });
  13.  
  14. return a.exec();
  15. }

mouselogger.h

Header file of class for logging messages about mouse events. In this file, you must declare static methods:

  1. To return an object reference singleton through which slot has been connected to the signal of the mouse event.
  2. Static method mouseProc, which will be used for event handling.
  1. #ifndef MOUSELOGGER_H
  2. #define MOUSELOGGER_H
  3.  
  4. #include <QObject>
  5. #include <windows.h>
  6.  
  7. class MouseLogger : public QObject
  8. {
  9. Q_OBJECT
  10. Q_DISABLE_COPY(MouseLogger)
  11. public:
  12. static MouseLogger &instance();
  13. explicit MouseLogger(QObject *parent = nullptr);
  14. virtual ~MouseLogger(){}
  15.  
  16. // Static method that will act as a callback-function
  17. static LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam);
  18.  
  19. signals:
  20. // The signal, which will report the occurrence of an event
  21. void mouseEvent();
  22.  
  23. public slots:
  24.  
  25. private:
  26. // hook handler
  27. HHOOK mouseHook;
  28. };
  29.  
  30. #endif // MOUSELOGGER_H

mouselogger.cpp

  1. #include "mouselogger.h"
  2. #include <QDebug>
  3.  
  4. MouseLogger &MouseLogger::instance()
  5. {
  6. static MouseLogger _instance;
  7. return _instance;
  8. }
  9.  
  10. MouseLogger::MouseLogger(QObject *parent) : QObject(parent)
  11. {
  12. HINSTANCE hInstance = GetModuleHandle(NULL);
  13.  
  14. // Set hook
  15. mouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, hInstance, 0);
  16. // Check hook is correctly
  17. if (mouseHook == NULL) {
  18. qWarning() << "Mouse Hook failed";
  19. }
  20. }
  21.  
  22. LRESULT CALLBACK MouseLogger::mouseProc(int Code, WPARAM wParam, LPARAM lParam)
  23. {
  24. Q_UNUSED(Code)
  25.  
  26. // Having an event hook, we nned to cast argument lParam
  27. // to the structure of the mouse is the hook.
  28. MOUSEHOOKSTRUCT * pMouseStruct = (MOUSEHOOKSTRUCT *)lParam;
  29.  
  30. // Next, we check to see what kind of event occurred,
  31. // if the structure is not a pointer to nullptr
  32. if(pMouseStruct != nullptr) {
  33. switch (wParam) {
  34. case WM_MOUSEMOVE:
  35. qDebug() << "WM_MOUSEMOVE";
  36. break;
  37. case WM_LBUTTONDOWN:
  38. qDebug() << "WM_LBUTTONDOWN";
  39. break;
  40. case WM_LBUTTONUP:
  41. qDebug() << "WM_LBUTTONUP";
  42. break;
  43. case WM_RBUTTONDOWN:
  44. qDebug() << "WM_RBUTTONDOWN";
  45. break;
  46. case WM_RBUTTONUP:
  47. qDebug() << "WM_RBUTTONUP";
  48. break;
  49. case WM_MBUTTONDOWN:
  50. qDebug() << "WM_MBUTTONDOWN";
  51. break;
  52. case WM_MBUTTONUP:
  53. qDebug() << "WM_MBUTTONUP";
  54. break;
  55. case WM_MOUSEWHEEL:
  56. qDebug() << "WM_MOUSEWHEEL";
  57. break;
  58. default:
  59. break;
  60. }
  61. emit instance().mouseEvent();
  62. }
  63.  
  64. // After that you need to return back to the chain hook event handlers
  65. return CallNextHookEx(NULL, Code, wParam, lParam);
  66. }

Result

The result will be to monitor the mouse events, regardless of whether the mouse cursor is in the focus of the program, if the application has a graphical user interface, or is not in the program focus.

Video

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…