[C++] start windows mouse hook example

2019. 7. 30. 22:55Development/C++

One of the Windows development techniques is called hooking. The advantage is that you can control it more easily than you think.
In addition, MSDN documentation exists because the technique is an official technology provided by MSDN.

 

https://docs.microsoft.com/en-us/windows/win32/winmsg/hooks

 

Hooks - Windows applications

Hooks In this article --> A hook is a point in the system message-handling mechanism where an application can install a subroutine to monitor the message traffic in the system and process certain types of messages before they reach the target window proced

docs.microsoft.com

Windows Message Hooking?

Hooking means putting your program into SPY on your system or another program.
For example, if a mouse click event message is generated when a mouse message is hooked, it is first detected through SPY and forwarded to the system.
At this time, hooking is a technique that allows you to perform actions such as forwarding other information to the Left Click Message as a Right Click Message, or transmitting it to the system that it has never clicked.
You can hook up keyboard messages as well as mouse messages to create a keyboard, or you can hook up all other messages to handle them.

 

Using WIndows Message Hooking

SPY ++ programs that are used by many developers are developed using this technique.
And I have a mouse gesture program that I am creating and using. I will explain this part later and I will make it together.

 

Warning

As you can see in the picture above, because it acts between the OS's Message Queue and the Application Message Queue, hooking must be implemented in the DLL rather than the type implemented by the EXE.
In other words, a DLL usually requires both an EXE and a DLL to be loaded.

 

SetWindowsHookExA

HHOOK SetWindowsHookExA( // Install Hooking
    __in int idHook, // HOOK TYPE
    __in HOOKPROC lpfn, // HOOK PROCEDURE
    __in HINSTANCE hmod, // DLL INSTANCE HANDLE
    __in DWORD dwThreadId
    );



BOOL UnhookWindowsHookEx( // UnInstall Hooking
    __in HHOOK hhk
    );

 

In EXE, you just LOAD the DLL and call the SetWindowsHookExA API from the actual DLL to install the hook.
If you're done, use UnhookWindowsHookEx to unhook it.

 

https://docs.microsoft.com/ko-kr/windows/win32/api/winuser/nf-winuser-setwindowshookexa

 

SetWindowsHookExA function (winuser.h)

Installs an application-defined hook procedure into a hook chain.

docs.microsoft.com

In the future, we will create a program with hooking.
Please look forward to!