Windows Programming _ sun Xin C ++ lesson20 hook and Database Access

Source: Internet
Author: User

Windows Programming _ sun Xin C ++ lesson20 hook and Database Access

Highlights of this section:
1. Hook programming review Windows message passing mechanism
2. install internal hooks
3. install global hooks
4. Preliminary understanding of Database Access Technology
//************************************** **************************************** ***************
1. Hook programming review Windows message passing mechanism
Shows the message mechanism for Windows:

2. install internal hooks: hooks related to a specified Thread
(1) Hook chain: Multiple hook processes form a hook chain, and the last installed hook is always in front of the chain. The hook chain allows multiple messages to be processed.
(2) install the hook and use the setwindowshookex function. The function is prototype:
Hhook setwindowshookex (
Int idhook, // hook type
Hookproc lpfn, // hook procedure
Hinstance hmod, // handle to application instance
DWORD dwthreadid // thread identifier
);
Parameter 1: The idhook parameter specifies the installed hook type.
Parameter 2: lpfn points to a function pointer of the hook process. If the dwthread parameter is set to 0 or is specified as the thread ID created by different processes, this parameter must be set to the hook process pointing to a dynamic link library (DLL. Otherwise, this parameter can point to a hook process related to the current process.
Parameter 3: The hmod parameter specifies the DLL handle of the hook process specified by the lpfn parameter, if the dwthread parameter is specified as the ID of a thread created by the current process and the Execution Code of the hook process is related to the current thread, this parameter must be set to null.
Parameter 4: The dwthreadid parameter specifies the Thread associated with the hook process,
When the parameter is set to 0, the hook process is related to all running threads on the same desktop as the current call thread.
Note:
First, the global hook must be a hook function in the dynamic link library.
Second, after calling the hook process, call the callnexthookex function to pass the message to the next hook process,
Unless you do not want other programs to accept the messages, this may cause errors in the hook process installed by other programs.
Third, call the unhookwindowshookex function before the program ends to release hook-related resources.
(3) Compile hook functions to compile different types of hook processes based on different types of hooks.
For example, the mouse hook composition function:
Lresult callback mouseproc (
Int ncode, // hook code
Wparam, // message identifier
Lparam // mouse coordinates
);
Description of the returned values of the mouseproc process:
If the ncode is less than 0, the callback process must return the return value of the callnexthookex function;
If the ncode is greater than or equal to 0 and the hook process does not process this message, it is strongly recommended to call the callnexthookex function and return its value,
Otherwise, other programs with mouse hooks installed cannot correctly receive the message, which may cause incorrect results. If the hook process processes the message,
A non-zero value is returned to prevent the system from sending the message to other programs.
For example, the function prototype of the keyboard hook process is:
Lresult callback keyboardproc (
Int code, // hook code
Wparam, // virtual-key code
Lparam // keystroke-message information
);
For Messages obtained during the keyboard hook process, wparam indicates the virtual key value of the key. You can use this virtual key value to determine the key.
The virtual key value is a set of macros (select the virtual key value and go to the definition to view it ), among them, the virtual key values from '0' to '9' and from 'A' to 'Z' are the same as the ASCII Code and are not macro-defined; the lparam parameter determines whether to press multiple keys at the same time.
(4) determine the user's Alt + F4 keyThe key is how to determine whether the Alt key is pressed.
You can use the lparam parameter of the keyboard message to determine this information. The lparam parameter of the keyboard key message is illustrated as follows (provided by msdn ):
How to determine whether it is achieved through shift and operation, see what I have drawn for the specific process:

(5) Main Code of the internal hook program (the code automatically added by the dialog box program is not listed) is as follows (note to exit the program by pressing F6 ):
//************************************** ***************************

[CPP]
View plaincopyprint?
  1. // Innerhookdlg. cpp
  2. Hhook g_hkeyhook = NULL;
  3. Hhook g_hmousehook = NULL;
  4. Hwnd g_hwnd = NULL; // Save the handle
  5. Lresult callback mouseproc (
  6. Int ncode, // hook code
  7. Wparam, // message identifier
  8. Lparam // mouse coordinates
  9. )
  10. {
  11. Return 1;
  12. }
  13. Lresult callback keyboardproc (
  14. Int code, // hook code
  15. Wparam, // virtual-key code
  16. Lparam // keystroke-message information
  17. )
  18. {
  19. /*
  20. If (vk_space = wparam | vk_return = wparam) // block spaces and enter keys
  21. If (vk_f4 = wparam & (1 = (lparam> 29 & 1) // mask the Alt + F4 key
  22. Return 1;
  23. Else
  24. Return callnexthookex (hhook, code, wparam, lparam); // continue to transmit messages to the hook chain
  25. */
  26. If (vk_f6 = wparam) // exit with the F6 key
  27. {
  28. : Sendmessage (g_hwnd, wm_close, 0, 0); // close the dialog box
  29. Unhookwindowshookex (g_hkeyhook );
  30. Unhookwindowshookex (g_hmousehook );
  31. }
  32. Return 1;
  33. }
  34. Bool cinnerhookdlg: oninitdialog ()
  35. {
  36. ...
  37. // Todo: add extra initialization here
  38. G_hwnd = m_hwnd; // get the handle of the dialog box
  39. G_hmousehook = setwindowshookex (wh_mouse, mouseproc, null, getcurrentthreadid (); // sets the mouse hook to block messages of the current process
  40. G_hkeyhook = setwindowshookex (wh_keyboard, keyboardproc, null, getcurrentthreadid (); // set the keyboard hook
  41. Return true; // return true unless you set the focus to a control
  42. }

 

//************************************** ****************************
3. install global hooks: hooks related to all threads
The global hook process must be a hook process in a dynamic link library (DLL. First, you must compile a dynamic link library hook. DLL for the hook process,
Then write a global hook hooktest to call the hook process in the dynamic link library.
(1) how to obtain the function module handle in the dynamic link library
Two methods are provided to obtain the module handle of the dynamic link library when writing a hook in the Dynamic Link Library:
Method 1: Use the parameter passed by the dllmain function to obtain the handle
Method 2: Use the getmodulehandle function. The prototype of the function is hmodule getmodulehandle (
Lptstr lpmodulename // Module name the default file suffix is DLL
);
(2)How to save the handle of the current running program
Define the global variable hwnd g_hwnd = NULL in the program. When the program switches to another window, press the custom close key F6 to close the program.
SolutionUse shared data segments, Define the window handle:
# Pragma data_seg ("myseg ")
Hwnd g_hwnd = NULL;
# Pragma data_seg ()
Set the read/write and share attributes of a section:
Method 1: complete writing in the source file is
//************************************** ****************************
# Pragma data_seg ("myseg ")
Hwnd g_hwnd = NULL; // It will be placed in the segment after initialization to view the command as dumpbin-headers hook. dll
# Pragma data_seg ()
// # Pragma comment (linker, "/section: myseg, RWS") // sets the read/write sharing attribute of the set.
//************************************** ****************************
Method 2: declare the following in the module definition file:
//************************************** ****************************
Segments
Myseg read write shared
//************************************** ****************************
Use dumpbin.exe to view program data segments and run the command dumpbin-headers hook. dll.
After setting the mysegdata segment reading, writing, and sharing, use dumpbin.exe to view the result, as shown in:

//************************************** ****************************
# The Pragma command has other usage instructions. For details, see msdn.
For more information about data sharing, see blog: http://www.cnblogs.com/ahuo/archive/2008/04/08/1143488.html
(3) the code for the hook DLL and the hook test program is as follows:
//************************************** ****************************

[CPP]
View plaincopyprint?
  1. // Hook. DLL Code
  2. // Hook. Def
  3. Library hook
  4. Exports
  5. Sethook
  6. Segments
  7. Myseg read write shared
  8. //************************************** ****************************
  9. // Hook. cpp
  10. # Include <windows. h>
  11. Hhook g_hmousehook = NULL; // handle of the mouse hook Process
  12. Hhook g_hkeyhook = NULL; // handle of the keyboard hook Process
  13. # Pragma data_seg ("myseg ")
  14. Hwnd g_hwnd = NULL; // It will be placed in the segment after initialization to view the command as dumpbin-headers hook. dll
  15. # Pragma data_seg ()
  16. // # Pragma comment (linker, "/section: myseg, RWS") // set the read/write sharing attribute of the set. This parameter is not required if it is specified in the module definition file.
  17. // Obtain the handle of the Dynamic Link Library module. method 1 use dllmain
  18. /* Hinstance g_hinst = NULL; // global instance handle variable
  19. // Dynamic link library entry function
  20. Bool winapi dllmain (
  21. Hinstance hinstdll, // handle to the DLL module
  22. DWORD fdwreason, // reason for calling function
  23. Lpvoid lpvreserved // Reserved
  24. )
  25. {
  26. G_hinst = hinstdll; // obtain the dynamic link library handle
  27. Return true;
  28. }*/
  29. Lresult callback mouseproc (
  30. Int ncode, // hook code
  31. Wparam, // message identifier
  32. Lparam // mouse coordinates
  33. )
  34. {
  35. Return true;
  36. }
  37. Lresult callback keyboardproc (
  38. Int code, // hook code
  39. Wparam, // virtual-key code
  40. Lparam // keystroke-message information
  41. )
  42. {
  43. If (vk_f6 = wparam)
  44. {
  45. : Sendmessage (g_hwnd, wm_close, 0, 0 );
  46. Unhookwindowshookex (g_hmousehook );
  47. Unhookwindowshookex (g_hkeyhook );
  48. }
  49. If ('A' = wparam)
  50. MessageBox (g_hwnd, "pressed! "," Hook Test ", mb_ OK );
  51. Return true;
  52. }
  53. Void sethook (hwnd)
  54. {
  55. G_hwnd = hwnd; // when declared as global, switching to other processes will change
  56. // Method 2: getmodulehandle
  57. G_hmousehook = setwindowshookex (wh_mouse, mouseproc, getmodulehandle ("Hook"), 0); // install the mouse hook
  58. G_hkeyhook = setwindowshookex (wh_keyboard, keyboardproc, getmodulehandle ("Hook"), 0); // install the keyboard hook
  59. }
  60. //************************************** ****************************
  61. // Hook Test Dialog Box program
  62. // Hooktest. cpp
  63. _ Declspec (dllimport) void sethook (hwnd); // import function injection and add the hook. lib and hook. DLL files to the current project.
  64. Bool chooktestdlg: oninitdialog ()
  65. {
  66. ...
  67. // Todo: add extra initialization here
  68. // Set to the top-layer full-screen window. the user cannot see other program windows.
  69. Int cxscreen, cyscreen;
  70. Cxscreen = getsystemmetrics (sm_cxscreen );
  71. Cyscreen = getsystemmetrics (sm_cyscreen );
  72. Setwindowpos (& wndtopmost, 0, 0, cxscreen, cyscreen, swp_showwindow );
  73. Sethook (m_hwnd); // start the hook
  74. Return true;
  75. }

//************************************** ****************************
Shows the effect of running the program (pay attention to exit the program by pressing F6 (Of course, the screen effects of the keyboard and mouse cannot be observed here.):

As shown in the following figure, the 360 security guard prompts a warning message when the program is running:

//************************************** ****************************
4. Preliminary understanding of Database Access Technology
(1) database access technical introduction is shown in:

(2) use ADO in VC to access the database
First, import the ADO database and use the following statement:
# Import "C: \ Program Files \ common files \ System \ ADO \ msado15.dll" no_namespace Rename ("EOF", "rseof ");
The file generated by the VC. the tlh can be used as the header file, and The Tli file can be used as the source file. A convenient way to obtain the database connection string is to create a TXT file and change the suffix to udl,
Open it and you can choose to connect to the database. After the selection, open it in TXT form to obtain the database connection string.
For system installation reasons, I just learned about the experiment and try again later.
//************************************** **************************************** ***************
Summary:
This section describes how to compile internal hooks and global hooks. To compile hooks with different functions, you can assign different parameters to the setwindowshookex function that creates hooks;
At the same time, I learned about several different database access technologies. Pay attention to choosing database access technologies in the future programming process.

Related Article

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.