What is hook programming?
This should start with the Windows message mechanism: When you click the left mouse button in the application window, the operating system will perceive this event, and then put the message in the application's message response queue, the application reads the message through getmessage and schedules the message to the operating system through dispatchmessage. The operating system calls the application window process function specified during the design window class to process the message.
If we want to block a special message, for example, if we want this application to not respond to carriage return or space messages, we need to intercept all the messages and then make judgments. If these two messages are used, block them. To implement this function, we can install a hook process, check during this process, and then decide whether to allow the message.
Let's look at the code first. Set a hook process in oninitdialog of the application in the dialog box:
G_hmouse = setwindowshookex (wh_mouse, // capture the mouse message mouseproc, // hook function null, // The specified Thread getcurrentthreadid () // The current thread
G_hmouse is a global variable function used to store the handle of the hook process, while mouseproc is a hook function corresponding to the mouse message. If this function returns a non-0 value, the system will not pass the message to the window function. Here we simply let it return 1:
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam){return 1;}
We ran the program and found that when the mouse moved to the program, the mouse turned into a waiting state. You cannot click OK or cancel. You can only press the button to exit the program.
Below we shield the keyboard Space key message: first set a hook
g_hKeyboard = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, NULL, GetCurrentThreadId());
Then, in the hook function, 1 is directly returned for the Space key.
LRESULT CALLBACK KeyboardProc( int code, WPARAM wParam, LPARAM lParam ){if(VK_SPACE == wParam){return 1;}else{return CallNextHookEx(g_hKeyboard,code,wParam,lParam);}}
Vk_space is the virtual key code corresponding to the Space key. A long time ago, the keyboards produced by various companies were different. To make windows compatible with different keyboards, Microsoft developed a virtual key code to make the same key (such as letter ), the operating system can be identified by the driver regardless of its location on various types of keyboards. The virtual key starts with VK. You can also view the vk_space definition to see other key codes. If you want to process the message in the hook function, call callnexthookex as the return value of the hook function.
If we want to block the Alt + F4 key, we can
if(VK_F4 == wParam && (1 == (lParam>>29 &1)))
If the 29th bits of lparam are 1, the Alt key is pressed. We can move lparam to the right by 29 digits, and then it can be connected to phase 1.
If we want to shield other keys, but press the F2 key program to exit, we should determine in the response to the key to determine whether it is F2, if so, it is necessary to send the Exit message. But when sending a message, you need to get the handle of the window. What should I do? However, we can only use one global handle and set it to m_hwnd in oninitdialog.
The content of the hook function is changed
if(VK_F2 == wParam){::SendMessage(g_hWnd,WM_CLOSE,0,0);UnhookWindowsHookEx(g_hKeyboard);UnhookWindowsHookEx(g_hMouse);}return 1;
The hook functions described above can only block the mouse and keyboard messages on the main thread of the current process. We can use global hooks to shield the mouse and keyboard messages of all running threads. However, this hook function must be in the dynamic link library. First, create a dynamic link library:
# Include <windows. h> hhook g_hmouse = NULL; lresult callback mouseproc (INT ncode, wparam, lparam) {return 1;} void sethook () {g_hmouse = setwindowshookex (wh_mouse, // mouse message mouseproc, // hook function getmodulehandle ("Hook"), // dynamic link library handle 0); // associated with all threads}
Specify the module definition file for it, set the export function name to sethook, and the serial number is 2
LIBRARY CH_20_HOOkEXPORTSSetHook @2
Then, create an MFC dialog box project and call the sethook () function in oninitdialog (of course, do not forget to declare it to: _ declspec (dllimport) void sethook (); and add the corresponding. LB ). Then build the program and run it. Then, you will find that the mouse messages of all processes are blocked.
Next we will add a hook function in the dynamic link library to shield keyboard messages. First, we cannot shield all keyboard messages, otherwise we will not be able to exit the program, but the strong can only restart. We can leave an F2 key for the Keyboard Message. When the F2 key is pressed, the program automatically exits. The exit of the program can be achieved by sending the wm_close message, but the handle of the current window needs to be obtained when sending the message. How can this be done? We can pass the window handle as a parameter, and then use a global variable to receive it in the DLL. Then we can get the handle in the hook function:
# Include <windows. h> hhook g_hmouse = NULL; hhook g_hkeyboard = NULL; hwnd g_hwnd; lresult callback mouseproc (INT ncode, wparam, lparam) {return 1;} lresult callback keyboardproc (INT code, wparam, lparam) {If (vk_f2 = wparam) {sendmessage (g_hwnd, wm_close,); unhookwindowshookex (g_hmouse); then (g_hkeyboard);} return 1 ;} void sethook (hwnd) {g_hwnd = hwnd; g_hmouse = setwindowshookex (wh_mouse, // mouse message mouseproc, // hook function getmodulehandle ("ch_20_hook "), // dynamically linked library handle 0); // related to all threads g_hkeyboard = setwindowshookex (wh_keyboard, keyboardproc, getmodulehandle ("ch_20_hook"), 0 );}
When you run the program, press F2 when the window is activated, the program can exit, but press F2 in another window, but cannot exit. This is different from our previous understanding of the DLL: As mentioned earlier, when the DLL is used by multiple processes, these processes can share the DLL code and data. Therefore, the global variable g_hwnd In the DLL should be shared by all processes. Press F2 in other processes to exit. But that's not the case. Why? This is because Windows adopts the write-time replication mechanism. When the DLL is shared by two processes, if the second process wants to modify the data, it will copy a new page. This is for the sake of security, because if the variable in the DLL is a pointer and the first process that calls the DLL modifies it, when the second process calls it, the pointer may already point to another place.
If you want the Global handle g_hwnd to be shared, you can put it in a shared section:
#pragma data_seg("MySec")HWND g_hWnd = NULL;#pragma data_seg()#pragma comment(linker,"/section:MySec,RWS")
Note: When shared variables must be initialized, use dumpbin-headers to view them. You can see:
Section header #5
Mysec name
104 virtual size
37000 virtual address
1000 size of raw data
35000 file pointer to raw data
0 file pointer to relocation table
0 file pointer to line numbers
0 Number of relocations
0 Number of line numbers
D0000040 flags
Initialized data
Shared
Read Write
Press F2 in any window to close the program.
In addition to specifying the attributes of a section using # pragma comment, you can also set the attributes of a shared section in the module definition file:
SEGMENTSMySec READ WRITE SHARED
The attribute name must be used here.