Hook entry [network arrangement]

Source: Internet
Author: User

Please download the source code of the vc6 program in the following documents from my resources

----------------- OK begin mouse --------------------------------

Http://www.programbbs.com/doc/1580.htm

Use Win32 system Hook Technology in VC ++ 6.0
Category: VC ++
Recommendation index:★★☆
Popularity: 334
Popularity this week: 1
Released on: 2007-5-8

Lang Rui, Institute of Electronics 22nd, Ministry of Information Industry

I. Introduction
The essence of a hook is a program used to process system messages. It is mounted to the system through system calls. There are many types of hooks. Each Hook can intercept and process the corresponding message. Each time a specific message is sent, the hook program intercepts the message before reaching the target window to gain control of the message. In this case, the hook function can process intercepted messages and even forcibly End message transmission. This is a bit similar to the pretranslatemessage function in MFC. The difference is that this function can only be used to intercept messages in the current process, but is powerless to system messages.
Ii. Win32 system hook implementation
Each type of Hook is maintained by the system. The recently installed hook is at the beginning of the chain and has the highest priority. The first installed hook is at the end of the chain. To implement a Win32 system hook, you must first call the SDK's API function setwindowshookex to install the hook function. Its prototype is:
Hhook setwindowshookex (INT idhook,
Hookproc lpfn,
Hinstance hmod,
DWORD dwthreadid );
Among them, the first parameter is the hook type, commonly used wh_mouse, wh_keyboard, wh_getmessage, and so on; The second parameter is the address of the hook function, call this function when the hook hooks any message. The third parameter is the handle of the module where the hook function is located; the fourth parameter is the ID of the hook-related function used to specify the thread to which the hook is to be hooked. If the value is 0, the system will intercept messages of the entire system. This is a global hook. If a specific thread is specified, it is a dedicated hook of the thread.
Global hook functions must be included in DLL (Dynamic Link Library), while thread-specific hooks can be included in executable files. After processing the message, the hook function that obtains control can call the callnexthookex API function in another SDK to continue to transmit the message. You can also discard the message by directly returning true to prevent delivery of the message.
When using global hook functions, you need to use dll as the carrier. There are three forms of mfc dll in vc6 to choose from, that is, regular statically linked to mfc dll (Standard static link mfc dll), regular using the shared mfc dll (Standard Dynamic Link mfc dll) and extension mfc dll (Extended mfc dll ). The first type of DLL is to link the used MFC code to the DLL during compilation. When executing the program, it does not need the support of other MFC dynamic link class libraries, but it is large; the second type of DLL is dynamically linked to the MFC class library at runtime, so it is small but dependent on the support of the MFC dynamic link class library. Both types of DLL can be used by the MFC program and Win32 program. The third type of DLL is dynamic connection, but as an extension of the MFC class library, it can only be used by the MFC program.
Iii. Win32 DLL
The entry and exit functions of Win32 DLL are both dllmain, which is different from Win16 DLL. This function is called whenever a process or thread loads or unmounts a DLL. Its prototype is:
Bool winapi dllmain (hinstance hinstdll, DWORD fdwreason, lpvoid lpvreserved); the first parameter indicates the DLL instance handle; the third parameter is retained; the second parameter specifies the status of the dynamic connection library currently called. It has four possible values: dll_process_attach (process loading), dll_thread_attach (thread loading), and dll_thread_detach (thread unloading), dll_process_detach (process uninstall ). In the dllmain function, you can identify the passed value of this parameter and initialize or clean the DLL according to different parameter values. In the Win32 environment, the space of all processes is independent of each other, which reduces the interaction between applications, but greatly increases the programming difficulty. When a process dynamically loads a DLL, the system automatically maps the DLL address to the private space of the process and copies the global data of the DLL to the process space, the global data values of the same DLL owned by each process are not necessarily the same. When the dll Memory is mapped to the process space, each process has its own global memory copy, and every new process that loads the DLL reinitializes this memory area, that is to say, the process can no longer share the DLL. Therefore, to share data among multiple processes in a Win32 environment, you must make necessary settings. One way is to separate the data to be shared, place it in an independent data segment, set the attribute of the segment to share, and create a DLL for Memory Sharing.

Iv. Global Data Sharing
You can use # pragma data_seg to create a new data segment and define shared data. The specific format is:
# Pragma data_seg (shareddata)
Hwnd sharedwnd = NULL; share data
# Pragma data_seg ()
All variables declared between data_seg pragmas statements are in the shareddata segment. Defining only one data segment can not achieve the purpose of sharing data, but also tell the compiler the attributes of this segment, there are two ways to achieve this (the effect is the same ), one way is in. add the following statement to the def file:
Setctions
Shareddata read write shared
Another method is to add the following statement to the project setting link option:
Sectionshareddata, RWS
V. Example of a mouse hook Program
The global hook function is used in this example. The program consists of the executable program mousedemo and the dynamic Connection Library mousehook. First, compile the MFC extended dynamic Connection Library mousehook. dll.
(1) Select MFC Appwizard (DLL) to create the project mousehook;
(2) Select the MFC extension DLL (MFC extension DLL) type;
(3) use the addtoproject sub-menu new… in the project menu... Add the header file mousehook. h.
(4) create a hook class in the header file:
Class afx_ext_class cmousehookpublic cobject
{
Public
Cmousehook (); constructor of the hook class
~ Cmousehook (); hook class destructor
Bool starthook (hwnd); install the hook function
Bool stophook (); uninstall Hook Function
};
(5) Add the # includemousehook. H Statement to the mousehook. cpp file;
(6) add global shared data variables:
# Pragma data_seg (mydata)
Hwnd glhprevtarwnd = NULL; the window handle pointed by the last mouse
Hwnd glhdisplaywnd = NULL; display the handle of the title edit box of the target window
Hhook glhhook = NULL; installed mouse hook handle
Hinstance glhinstance = NULL; DLL instance handle
# Pragma data_seg ()
(7) define the segment attribute in the def file:
Sections
Mydata read write shared
(8) Add the statement for saving the DLL instance handle to the dllmain function of the main file mousehook. cpp:
Extern C int apientry
Dllmain (hinstance, DWORD dwreason, lpvoid lpreserved)
{
Unreferenced_parameter (lpreserved );
If (dwreason = dll_process_attach)
{
If (! Afxinitextensionmodule (mousehookdll, hinstance ))
Return 0;
New cdynlinklibrary (mousehookdll );
Glhinstance = hinstance; insert and save the DLL instance handle
}
Else if (dwreason = dll_process_detach)
{
Afxtermextensionmodule (mousehookdll );
}
Return 1; OK
}
The most important part of this function is to call afxinitextensionmodule (), which initializes the DLL so that it works correctly in the MFC framework. It must be passed to the DLL instance handle of dllmain () and the afx_extension_module structure. The structure contains useful information for MFC.
(9) Implementation of member functions of class cmousehook:
Cmousehookcmousehook () Class Constructor
{
}
Cmousehook ~ Cmousehook () Class destructor
{
Stophook ();
}
Install the hook in bool cmousehookstarthook (hwnd) and set the handle of the receive display window.
{
Bool bresult = false;
Glhhook = setwindowshookex (wh_mouse, mouseproc, glhinstance, 0 );
If (glhhook! = NULL)
Bresult = true;
Glhdisplaywnd = hwnd; set the handle to display the title edit box of the target window.
Return bresult;
}
Bool cmousehookstophook () uninstall hook
{
Bool bresult = false;
If (glhhook)
{
Bresult = unhookwindowshookex (glhhook );
If (bresult)
{
Glhprevtarwnd = NULL;
Glhdisplaywnd = NULL; clear the variable
Glhhook = NULL;
}
}
Return bresult;
}
(10) Implementation of Hook Functions
Lresult winapi mouseproc (INT ncode, wparam, lparam)
{
Lpmousehookstruct pmousehook = (mousehookstruct far) lparam;
If (ncode = 0)
{
Hwnd glhtargetwnd = pmousehook-hwnd; get the target window handle
Hwnd parentwnd = glhtargetwnd;
While (parentwnd! = NULL)
{
Glhtargetwnd = parentwnd;
Parentwnd = getparent (glhtargetwnd); obtains the handle of the main application window.
}
If (glhtargetwnd! = Glhprevtarwnd)
{
Char szcaption [100];
Getwindowtext (glhtargetwnd, szcaption, 100); the title of the target window.
If (iswindow (glhdisplaywnd ))
Sendmessage (glhdisplaywnd, wm_settext, 0, (lparam) (lpctstr) szcaption );
Glhprevtarwnd = glhtargetwnd; Save the target window
}
}
Return callnexthookex (glhhook, ncode, wparam, lparam); continue to pass messages
}
After compilation, you can obtain the dynamic Connection Library mousehook. dll and the mousehook. Lib used in the link for the mouse hook required for running.
Vi. Integration
Next we will create a new hook executable program that calls the mouse hook to dynamically connect to the database:
(1) Use the Appwizard (exe) of MFC to create the project mousedemo;
(2) Select a dialog-based application and save the remaining steps;
(3) add an edit box idc_edit1 to the dialog box;
(4) Add the inclusion statement for mousehook. h to mousedemo. h: # includemousehook. h;
(5) Add the private data member cmousehook m_hook in the cmousedemodlg. H class definition;
(6) Add the following content after the todo comment of the oninitdialog function:
Cwnd pwnd = getdlgitem (idc_edit1); get the class pointer in the edit box
M_hook.starthook (pwnd-getsafehwnd (); get the window handle in the edit box and install the hook
(7) link the dll library to add mousehook. lib to the project setting link tag;
(8) Copy mousehook. h and mousehook. lib to the mousedemo project directory and mousehook. DLL to the DEBUG directory. Compile and execute the program. When the mouse slides over the window, the title of the window is displayed in the edit box.
Conclusion:
The system hook has very powerful functions. Through this technology, almost all windows
System messages are intercepted, monitored, and processed. This technology can be widely used in a variety of software, especially the need
Software that monitors the system, such as monitoring and automatic recording. This program only intercepts mouse messages,
You can also apply this technology to the keyboard, port, and other functions in the Win32 environment.

From: World Network

 

Bytes ---------------------------------------------------------------------------------------------------

Global hook details
Http://www.programbbs.com/doc/3164.htm
Category: VC ++
Recommendation index:★★★☆
Popularity: 3330
Popularity this week: 32
Release date:
Monitoring Program Implementation
We found that some Trojans or other virus programs often record the operation messages of our keyboard or mouse, and then send them to their designated places for listening. this function uses a global hook to intercept the mouse or Keyboard Message and obtain the operated message. to get control of the mouse and keyboard, we need to use the setwindowshookex function.
Hhook setwindowshookex (
Int idhook, type of hook to install
Hookproc lpfn, address of hook procedure
Hinstance hmod, handle to application instance
DWORD dwthreadid identity of thread to install hook
);
Idhook is the hook type to be installed. lpfn is the message processing process of the hook function, hmod is the application instance handle, and dwthreadid is the thread for which to install the hook. if it is 0, the hook is installed for all threads, that is, the global hook. this is the start to get control of all application messages. there are many hook types we have installed:
Bytes
Wh_mouse is the mouse hook and wh_keyboard is the keyboard hook.
Different hooks correspond to different hook processes. The method of writing the hook process (take the keyboard hook process as an example) is
Lresult callback mouseproc (
Int ncode, hook code
Wparam, message identifier
Lparam mouse coordinates
);
The name of the hook process does not matter.
You can use unhookwindowsex to cancel hook installation.
Bool unhookwindowshookex (
Hhook HHK handle to hook procedure to remove
);

The following describes how to install the hook function for each application and how to install the hook for each application to use the knowledge of the dynamic link library, use a dynamic link library to load data to each application.
First, we use vc6.0 to create an empty project for Windows dynamic link library, and create a header file to dynamically link the library itself and applications that use dynamic link library, we have defined the macro and custom message import and export as well as the function to be imported and exported.
Hookdll. h
Define the function modifier macro to reference the export function of this DLL project.
# Ifdef keyhooklib_exports
# Define keyhooklib_api _ declspec (dllexport) Export macro
# Else
# Define keyhooklib_api _ declspec (dllimport) Import macro
# Endif
Custom messages for communication with the main program
# Define hm_key wm_user + 101 custom Keyboard Message
# Define hm_mouse wm_user + 102 custom mouse message
Declare the function to be exported
Bool keyhooklib_api winapi setkeyhook (bool binstall,
DWORD dwthreadid = 0, hwnd hwndcaller = NULL );
Bool keyhooklib_api winapi setmousehook (bool binstall,
DWORD dwthreadid = 0, hwnd hwndcaller = NULL

Create another c ++ source file, hookdll. cpp.
We should first include the windows. h header file
Then define # define keyhooklib_exports to export macros when hookdll. H is included,
# Include hookdll. h
# Pragma data_seg (ycishared)
Hwnd g_hwndcaller = NULL; Save the main window handle
Hhook g_hhook = NULL; Save the hook handle
Hhook g_hmousehook = NULL;
# Pragma data_seg ()
We have defined the shared global window handle and the global hook identifier for all applications to share these three variables.
The following is the implementation code of the hook function.
Hmodule winapi modulefromaddress (pvoid PV) obtains the URL of the hook function.
{
Memory_basic_information MBI;
If (virtualquery (PV, & MBI, sizeof (MBI ))! = 0)
{
Return (hmodule) MBI. allocationbase;
}
Else
{
Return NULL;
}
}
Lresult callback keyhookproc (INT ncode, wparam, lparam) keyboard hook function message process
{
If (ncode 0 ncode = hc_noremove)
Return callnexthookex (g_hhook, ncode, wparam, lparam );

If (lparam & 0x40000000) The Message repeats and is handed over to the next hook chain.
{
Return callnexthookex (g_hhook, ncode, wparam, lparam );
}

Main Notification window. The wparam parameter is a virtual key code, and the lparam parameter contains information about this key.
Postmessage (g_hwndcaller, hm_key, wparam, lparam); send custom keyboard messages
Return callnexthookex (g_hhook, ncode, wparam, lparam );
}
Bool winapi setkeyhook (bool binstall, DWORD dwthreadid, hwnd hwndcaller) to install and uninstall Hook Functions
{
Bool Bok;
G_hwndcaller = hwndcaller;

If (binstall)
{
G_hhook = setwindowshookex (wh_keyboard, keyhookproc,
Modulefromaddress (keyhookproc), dwthreadid); install the keyboard hook
Bok = (g_hhook! = NULL );
}
Else
{
Bok = unhookwindowshookex (g_hhook );
G_hhook = NULL;
}

Return Bok;
}
Lresult callback mouseproc (INT ncode, wparam, lparam)
{
If (ncode 0 ncode = hc_noremove)
Return callnexthookex (g_hmousehook, ncode, wparam, lparam );
Postmessage (g_hwndcaller, hm_mouse, wparam, lparam); send custom mouse messages
Return callnexthookex (g_hmousehook, ncode, wparam, lparam );
}
Bool winapi setmousehook (bool binstall, DWORD dwthreadid, hwnd hwndcaller)
{
Bool Bok;
G_hwndcaller = hwndcaller;
If (binstall)
{
G_hmousehook = setwindowshookex (wh_mouse, mouseproc,
Modulefromaddress (mouseproc), dwthreadid); install the mouse hook
Bok = (g_hmousehook! = NULL );
}
Else
{
Bok = unhookwindowshookex (g_hmousehook );
G_hmousehook = NULL;
}
Return Bok;
}
Finally, create a hookdll. Def module definition file under the project directory. Write the following code:
Library hookdll
Exports indicates the name of the export Function
Setkeyhook
Setmousehook
Sections specifying the shared field
Ycishared read write shared
When the module definition file is used, you can directly call the function by the function name when using the dynamic link library. Otherwise, the function cannot be found. in fact, the module definition file is used to prevent dynamic library name adaptation.

With the dynamic link library, we also need to use an application to set and record our mouse and keyboard records.
Create a dialog box-based MFC Application Project hookapp. First, add the implementation code for the required message response for our custom message.
Add the comment macro under protected of the header file of the dialog box class
Afx_msg longonhookkey (wparam, lparam );
Afx_msg longonhookmouse (wparam, lparam );
Specify the message processing function.
Begin_message_map (chookappdlg, cdialog)
Add the following code to the end_message_map
On_message (hm_key, onhookkey)
On_message (hm_mouse, onhookmouse)
After definition, write the implementation function in the source file.
Long chookappdlgonhookkey (wparam, lparam)
{
At this time, the wparam parameter is the virtual key code of the user's buttons,
The lparam parameter contains information such as the number of repeat times, scan code, and status of the previous button.
Char szkey [80];
Getkeynametext (lparam, szkey, 80); obtain the key name
Cstring stritem;
Stritem. Format (User buttons: % s, szkey );
Clistbox plistctrl = (clistbox) This-getdlgitem (idc_list1 ));
Plistctrl-insertstring (-1, stritem );
Cfile myfile;
Char content;
If (! Myfile. Open (this-mydocumentdir,
Cfilemoderead cfilemodewrite ))
{
Myfile. Open (this-mydocumentdir,
Cfilemodecreate );
Return 0;
}
Myfile. seektoend (); move the record pointer to the end
Plistctrl-gettext (plistctrl-getcount ()-1, stritem );
Content = stritem. getbuffer (max_path );
Myfile. Write (content, stritem. getlength ());
Ctime today = ctimegetcurrenttime ();
Cstring STR = today. Format (TT % Y % m % d % H % m % SRN );
Myfile. Write (Str. getbuffer (Str. getlength (), str. getlength ());
Myfile. Close ();
Return 0;
}
Long chookappdlgonhookmouse (wparam, lparam)
{
Lpmousehookstruct pmousehook = (mousehookstruct far) lparam;
Cstring stritem, strtext;
Clistbox plistctrl = (clistbox) This-getdlgitem (idc_list1 ));
Cpoint point;
Getcursorpos (& Point );
Clienttoscreen (& Point );
Cwnd pwnd = cwndgetforegroundwindow ();
If (pwnd)
{
Char STR [80];
Pwnd-getwindowtext (STR, 80 );
Strtext. Format (window % s, STR );
}
Cstring STR;
Cstring tempstr;
Clienttoscreen (& pmousehook-Pt );
Int X, Y;
X = pMouseHook-pt.x;
Y = pMouseHook-pt.y;
Tempstr. Format (x = % d, y = % d, x, y );
Strtext + = tempstr;
If (wparam = wm_rbuttondown)
{
Str. Format (right-click the position X = % d, y = % d, point. X, point. y );
Strtext + = STR;
Plistctrl-insertstring (-1, strtext );
This-savetofile (strtext, plistctrl );
}
If (wparam = wm_lbuttondblclk)
{
Screentoclient (& Point );
Str. Format (left-click position X = % d, y = % d, point. X, point. y );
Strtext + = STR;
Plistctrl-insertstring (-1, strtext );
This-savetofile (strtext, plistctrl );
}
If (wparam = wm_lbuttondown)
{
Str. Format (left-click position X = % d, y = % d, point. X, point. y );
MessageBox (strtext );
Strtext + = STR;
Plistctrl-insertstring (-1, strtext );
This-savetofile (strtext, plistctrl );
}
Return 0;
}
Void chookappdlgsavetofile (cstring strtext, clistbox plistctrl)
{
Char content;
Cfile myfile;
If (! Myfile. Open (this-mydocumentdir,
Cfilemoderead cfilemodewrite ))
{
Myfile. Open (this-mydocumentdir,
Cfilemodecreate );
Plistctrl-insertstring (-1, failed );
Return;
}
Myfile. seektoend ();
Content = strtext. getbuffer (strtext. getlength ());
Myfile. Write (content, strtext. getlength ());
Ctime today = ctimegetcurrenttime ();
Cstring strtime = today. Format (TT % Y % m month % d % H % m % SRN );
Myfile. Write (strtime. getbuffer (strtime. getlength (), strtime. getlength ());
Myfile. Close ();
}
The code above is the code that adds the operation message of the mouse message and the keyboard message to a list box and records it to a file. here, this-mydocumentdir is the file path to which you want to record operation messages.

When the dialog box is initialized
If (! Setkeyhook (true, 0, m_hwnd ))
MessageBox (Hook Installation failed !);
If (! Setmousehook (true, 0, m_hwnd ))
MessageBox (Hook Installation failed !);

Finally
Void chookappdlgondestroy ()
{
Setkeyhook (fasle); cancel the installation hook
Setmousehook (false); cancel hook Installation
}

This is the listening code for mouse and keyboard messages. You can also install other types of hooks for applications.

 

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.