Hook Simple example-block mouse and keyboard messages (i)

Source: Internet
Author: User

Hooks are the processing platform for intercepting and monitoring some of the Windows system's messages or API functions, allowing them to get information that they are interested in based on the programmer's settings.

Here is the main introduction of hooks to intercept mouse messages and keyboard messages.

The following is the callback Proc callback function and the CallNextHookEx function

LRESULT CALLBACK HookProc
(
int NCode,Specifies whether the message needs to be processed
WPARAM WPARAM,
LPARAM LPARAMAn additional message that contains the message,
);
The name of this callback function can be taken with you, but the form can certainly meet the above requirements, in fact, the callback function of the hook and Windows almost a virtue. Look at the return value of the hook function, if it returns a value other than 0, indicating that we have processed the message ourselves, the message is not passed to the target window procedure.
Look at Lresult CallNextHookEx.
(Hhook hhk;
int NCode;
WPARAM WPARAM;

LPARAM LPARAM;) This function passes the hook information to the next hook function, which can be understood as releasing the vehicle to the next checkpoint, which can be called according to your own needs. If we only set a hook function, then we assume that the hook message is passed CallNextHookEx to the next hook function, because it does not exist, so it passes back to the target window function.

Create an MFC Basedialog Project first


XXXDlg.cpp Code

MbHookDlg.cpp:implementation file//#include "stdafx.h" #include "MbHook.h" #include "MbHookDlg.h" #include " Afxdialogex.h "#ifdef _debug#define New debug_new#endif//CAboutDlg dialog used for App aboutclass caboutdlg:public cdial Ogex{public:caboutdlg ();//Dialog dataenum {IDD = idd_aboutbox};p rotected:virtual void DoDataExchange (cdataexchange*    PDX); DDX/DDV support//Implementationprotected:declare_message_map ()}; Caboutdlg::caboutdlg (): CDialogEx (Caboutdlg::idd) {}void CAboutDlg::D odataexchange (cdataexchange* pDX) {CDialogEx: :D Odataexchange (PDX);} Begin_message_map (CAboutDlg, CDialogEx) End_message_map ()//Cmbhookdlg Dialogcmbhookdlg::cmbhookdlg (CWnd* pParent/* =null*/): CDialogEx (Cmbhookdlg::idd, pparent) {m_hicon = AfxGetApp ()->loadicon (IDR_MAINFRAME);} void Cmbhookdlg::D odataexchange (cdataexchange* pdx) {cdialogex::D odataexchange (PDX);} Begin_message_map (Cmbhookdlg, CDialogEx) On_wm_syscommand () On_wm_paint () On_wm_querydragicon () END_MESSAGE_MAP () <span style= "color: #3333ff;" &The process function of Gt;<////////////////////////////////////////////////////////////hook hhook hook; HWND hwnd; LRESULT CALLBACK Messageboxproc (INT ncode,wparam wparam,lparam LPARAM) {if (ncode<0) return CallNextHookEx (Hook, Ncode,wparam,lparam); if (WParam = = vk_f3)//when pressing "F3" key to unload Hook{enddialog (hwnd,null);//Close Window UnhookWindowsHookEx (hook);// Unload hook function}else{return 1;}} </span>//Cmbhookdlg message Handlersbool cmbhookdlg::oninitdialog () {cdialogex::oninitdialog ();//Add "about The menu item to system menu.//Idm_aboutbox must is in the System command range. ASSERT ((Idm_aboutbox & 0xfff0) = = Idm_aboutbox); ASSERT (Idm_aboutbox < 0xf000); cmenu* Psysmenu = GetSystemMenu (FALSE); if (psysmenu! = NULL) {BOOL bnamevalid; CString straboutmenu;bnamevalid = straboutmenu.loadstring (Ids_aboutbox); ASSERT (Bnamevalid), if (!straboutmenu.isempty ()) {Psysmenu->appendmenu (mf_separator);p Sysmenu->appendmenu ( Mf_string, Idm_aboutbox, Straboutmenu);}}  Set The icon for this dialog. The framework does this automatically//When the application ' s main window was not a Dialogseticon (M_hicon, TRUE);//Set Big Iconseticon (M_hicon, FALSE);//Set Small icon//todo:add Extra initialization here<span style= "color: #3333ff;" >hwnd= M_hwnd;hook=setwindowshookex (//wh_mouse//set mouse hook wh_keyboard//set keyboard hooks, Messageboxproc,null,  GetCurrentThreadID ()); </span>return TRUE; Return TRUE unless you set the focus to a control}void Cmbhookdlg::onsyscommand (UINT nid, LPARAM LPARAM) {if (NID &amp ; 0XFFF0) = = Idm_aboutbox) {CAboutDlg dlgabout;dlgabout.domodal ();} Else{cdialogex::onsyscommand (NID, LParam);}}  If you add a Minimize button to your dialog, you'll need the code below//to draw the icon. For MFC applications using the Document/view model,//This is automatically do for your by the framework.void Cmbhookdlg :: OnPaint () {if (Isiconic ()) {CPAINTDC DC (this);//device context for Paintingsendmessage (WM_ICONERASEBKGND, Reinterpret_cast<wparam> (DC. GETSAFEHDC ()), 0);//Center icon in client Rectangleint CXIcon = GetSystemMetrics (sm_cxicon); int cyicon = GetSystemMetrics (Sm_cyicon); CRect rect; GetClientRect (&rect); int x = (rect. Width ()-Cxicon + 1)/2;int y = (rect. Height ()-Cyicon + 1)/2;//Draw the ICONDC. DrawIcon (x, y, m_hicon);} Else{cdialogex::onpaint ();}} The system calls this function to obtain the cursor to display while the user drags//the minimized window. Hcursor Cmbhookdlg::onquerydragicon () {return static_cast
Setwindowshook () Mounting hooks:

Hhook SetWindowsHookEx (

int Idhook,//hook type, that is, it handles the message type HookProc LPFN,//The address pointer of the Hook subroutine. If the dwThreadID parameter is 0//or the identity of a thread created by another process,//LPFN must point to the hook in the DLL. In addition, LPFN can point to a section of the current process's hook code. The entry address of the hook function, which is called when the hook is hooked to any message. HINSTANCE Hmod,//handle to the application instance. Identifies the DLL that contains the Cheng referred to by LPFN. If dwThreadID identifies a thread created by the current process,//and the subroutine code is in the current process, hmod must be null. It is easy to set an instance handle for this application. DWORD dwThreadID//identifier of the thread associated with the installed hook child threads. If 0, the hook thread is associated with all threads, which is the global hook. ); The Idhook parameter can be the following choice:

Each type of hook enables applications to monitor different types of system message handling mechanisms. All available hook types are described below. 1.Wh_callwndprocAndWh_callwndprocretHookswh_callwndproc and Wh_callwndprocret hooks enable you to monitor messages sent to a window procedure. The system calls the Wh_callwndproc hook thread before the message is sent to the receive window procedure, and calls the Wh_callwndprocret hook after the window procedure finishes processing the message. The Wh_callwndprocret hook passes the pointer to the CWPRETSTRUCT structure, which is then passed to the hook path. The CWPRETSTRUCT structure contains the return value of the window procedure from which the message was processed, and also includes the message parameters associated with the message. 2.WH_CBTHook before the following events, the system calls the WH_CBT hook, which includes: 1) Activate, build, destroy, minimize, maximize, move, resize, etc. window events, 2) Complete system instructions, 3) move mouse from System message queue, keyboard event ; 4) set input focus events; 5) synchronize system Message Queuing events. The return value of the hook determines whether the system allows or prevents one of these operations. 3.Wh_debugHook the system calls the Wh_debug hook before the hook thread that is associated with the other hooks in the system call system. You can use this hook to decide whether to allow the system to invoke a hook that is associated with another hook. 4.Wh_foregroundidleHook when the foreground thread of an application is idle, you can use the Wh_foregroundidle hook to perform a low-priority task. When the foreground thread of the application is about to become idle, the system calls the Wh_foregroundidle hook thread. 5.Wh_getmessageThe hook application uses wh_getmessage hooks to monitor messages returned from the GETMESSAGE or PeekMessage function. You can use the Wh_getmessage hook to monitor mouse and keyboard input, as well as other messages sent to the message queue. 6.Wh_journalplaybackHookwh_journalplayback hooks enable applications to insert messages into the system message queue. You can use this hook to replay successive mouse and keyboard events recorded by using the Wh_journalrecord hook. As long as the Wh_journalplayback hook has been installed, normal mouse and keyboard events are invalid. The Wh_journalplayback Hook is a global hook that cannot be used as a thread-specific hook. Wh_journalplayback Hook returns the timeout value, which tells the system how long (in milliseconds) to wait before processing the current message from the playback hook. This allows the hook to control the playback of real-time events. Wh_journalplayback are system-wide local hooks and they will not be injected into any travel address space. 7.Wh_journalrecordHookwh_journalrecord hooks are used to monitor and record input events. Typically, this hook can be used to record successive mouse and keyboard events, and then back and forth by using the Wh_journalplayback hook. The Wh_journalrecord Hook is a global hook that cannot be used as a thread-specific hook. Wh_journalrecord are system-wide local hooks and they will not be injected into any travel address space. 8.Wh_keyboardHook in the application, Wh_keyboard hooks are used to monitor wm_keydown and WM_KEYUP messages, which are returned by GetMessage or PeekMessage function. You can use this hook to monitor keyboard messages entered into the message queue. 9.Wh_keyboard_llThe Hookwh_keyboard_ll hook monitors the keyboard messages entered into the thread message queue. 10.Wh_mouseHookwh_mouse Hooks monitor Mouse messages returned from the GetMessage or PeekMessage functions. Use this hook to monitor mouse messages entered into the message queue. 11.Wh_mouse_llHOOKWH_MOUSE_LL Hooks monitor Mouse messages that are entered into the thread message queue. 12.Wh_msgfilterAndWh_sysmsgfilterHookswh_msgfilter and Wh_sysmsgfilter hooks enable us to monitor menus, scroll bars, message boxes, dialog messages and discover that users use ALT + TAB or ALT+ESC key combinations to switch windows. Wh_msgfilter hooks can only monitor messages that are passed to a menu, scroll bar, message box, and messages that are passed to a dialog box created by an application that has a hook thread installed. Wh_sysmsgfilter Hooks monitor all application messages. Wh_msgfilter and Wh_sysmsgfilter hooks allow us to filter messages during the pattern cycle, which is equivalent to filtering messages in the main message loop. The Wh_msgfilter Hook can be called directly by calling Callmsgfilter function. By using this function, the application can use the same code to filter the message during the pattern loop, as in the main message loop. 13.Wh_shellThe hook shell application can use the Wh_shell hook to receive important notifications. When the shell application is active and the When top layer window is created or destroyed, the system calls the Wh_shell hook thread. Wh_shell a total of 5 minutes: 1) As long as a top-level, unowned window is generated, functioning, or destroyed; 2) when taskbar needs to redraw a button; 3) when the system needs to display a minimized form of a program about taskbar 4) When the keyboard layout status changes today, 5) when the user presses CTRL+ESC to execute task Manager (or the same level of program). As a rule, shell applications do not receive Wh_shell messages. Therefore, before an application can receive Wh_shell messages, the application must call SystemParametersInfo function to register itself. That is, if your app does not call the following code to register itself before, then it will never respond to your shellproc://minimizedmetrics mm = {sizeof (minimizedmetrics), 0,0, arw_hide};minimizedmetrics mm = {sizeof (minimizedmetrics), 0,0, 0, arw_hide};SystemParametersInfo (spi_setminimizedmetrics, sizeof (minimizedmetrics), &mm, 0);



Hook Simple example-block mouse and keyboard messages (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.