XML 注释

并非用于 XML 分析器的内容(例如与文档结构或编辑有关的说明)可以包含在注释中。 注释以 <!– 开始并以 —> 结束,例如 <!–catalog last updated 2000-11-01–>

注释可以出现在文档序言中,包括文档类型定义 (DTD);文档之后;或文本内容中。 注释不能出现在属性值中。 不能出现在标记中。

分析器在遇到 > 时,就认为注释已结束;然后继续将文档作为正常的 XML 处理。 因此,字符串 > 不能出现在注释中。 除了该限制之外,任何合法的 XML 字符均可以出现在注释中,与 CDATA 节非常类似。 这样,可以从分析器看到的输出流中删除 XML 注释,同时又不会删除文档的内容。

以下注释可以用于暂时除去标记。

<!--- <test pattern="SECAM" /><test pattern="NTSC" /> -->
说明说明
在 HTML 中,可以使用注释来隐藏脚本和样式表。 若要在 XML 中使用此方法,可能必须检索注释,提取注释的内容,检查是否有标记字符,然后再进行重新分析。 在此例中,CDATA 节是更好的选择。

Sample Code – Virtual Method Table hooking

Whenever a class defines a virtual function (or method), most compilers add a hidden member variable to the class which points to a virtual method table (VMT or Vtable). This VMT is basically an array of pointers to (virtual) functions. At runtime these pointers will be set to point to the right function, because at compile time, it is not yet known if the base function is to be called or a derived one implemented by a class that inherits from the base class. The code below shows an example of a typical VMT hook in Microsoft Windows.

class VirtualTable {  // example class  
 public:  
 virtual void VirtualFunction01( void );  
};

void VirtualTable::VirtualFunction01( void )  {  
  printf("VirtualFunction01 called");  
}

typedef void ( __thiscall* VirtualFunction01_t )( void* thisptr );  
VirtualFunction01_t g_org_VirtualFunction01;

 //our detour function  
void __fastcall hk_VirtualFunction01( void* thisptr, int edx )  {  
  printf("Custom function called");  
  //call the original function  
  g_org_VirtualFunction01(thisptr);  
}  
int _tmain(int argc, _TCHAR* argv[])  {

 DWORD oldProtection;

 VirtualTable* myTable = new VirtualTable();  
 void** base = *(void***)myTable;

 VirtualProtect( &base[0], 4, PAGE_EXECUTE_READWRITE, &oldProtection );  
 //save the original function  
 g_org_VirtualFunction01 = (VirtualFunction01_t)base[0];  
 //overwrite  
 base[0] = &hk_VirtualFunction01;  
 VirtualProtect( &base[0], 4, oldProtection, 0 );

 //call the virtual function (now hooked) from our class instance  
 myTable->VirtualFunction01();

 return 0;  
}

C# keyboard event hook[edit]

The following example will hook into keyboard events in Microsoft Windows using the Microsoft .NET Framework.

using System.Runtime.InteropServices;

namespace Hooks
{
    public class KeyHook
    {
        /* Member variables */
        protected static int Hook;
        protected static LowLevelKeyboardDelegate Delegate;
        protected static readonly object Lock = new object();
        protected static bool IsRegistered = false;

        /* DLL imports */
        [DllImport("user32")]
        private static extern int SetWindowsHookEx(int idHook, LowLevelKeyboardDelegate lpfn,
            int hmod, int dwThreadId);

        [DllImport("user32")]
        private static extern int CallNextHookEx(int hHook, int nCode, int wParam, KBDLLHOOKSTRUCT lParam);

        [DllImport("user32")]
        private static extern int UnhookWindowsHookEx(int hHook);

        /* Types & constants */
        protected delegate int LowLevelKeyboardDelegate(int nCode, int wParam, ref KBDLLHOOKSTRUCT lParam);
        private const int HC_ACTION = 0;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_KEYUP = 0x0101;
        private const int WH_KEYBOARD_LL = 13;

        [StructLayout(LayoutKind.Sequential)]
        public struct KBDLLHOOKSTRUCT
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }

        /* Methods */
        static private int LowLevelKeyboardHandler(int nCode, int wParam, ref KBDLLHOOKSTRUCT lParam)
        {
            if (nCode == HC_ACTION)
            {
                if (wParam == WM_KEYDOWN)
                    System.Console.Out.WriteLine("Key Down: " + lParam.vkCode);
                else if (wParam == WM_KEYUP)
                    System.Console.Out.WriteLine("Key Up: " + lParam.vkCode);
            }
            return CallNextHookEx(Hook, nCode, wParam, lParam);
        }
        
        public static bool RegisterHook()
        {
            lock (Lock)
            {
                if (IsRegistered)
                    return true;
                Delegate = LowLevelKeyboardHandler;
                Hook = SetWindowsHookEx(
                    WH_KEYBOARD_LL, Delegate,
                    Marshal.GetHINSTANCE(
                        System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]
                    ).ToInt32(), 0
                );

                if (Hook != 0)
                    return IsRegistered = true;
                Delegate = null;
                return false;
            }
        }

        public static bool UnregisterHook()
        {
            lock (Lock)
            {
                return IsRegistered = (UnhookWindowsHookEx(Hook) != 0);
            }
        }
    }
}

Hooks Overview

A hook is a mechanism by which an application can intercept events, such as messages, mouse actions, and keystrokes. A function that intercepts a particular type of event is known as a hook procedure. A hook procedure can act on each event it receives, and then modify or discard the event.

The following some example uses for hooks:

  • Monitor messages for debugging purposes
  • Provide support for recording and playback of macros
  • Provide support for a help key (F1)
  • Simulate mouse and keyboard input
  • Implement a computer-based training (CBT) application
Note  Hooks tend to slow down the system because they increase the amount of processing the system must perform for each message. You should install a hook only when necessary, and remove it as soon as possible.

 

Using global windows hook in Visual C++

Using global windows hook in Visual C++

Since you are here, you probably know what is a Windows hook and what can it be used for. I say this because, this isn’t exactly a beginner topic. Nonetheless, lets get ourselves familiar with hooks before we get started. Here is how the MSDN documentation describes a Windows hook:

A hook is a mechanism by which an application can intercept events, such as messages, mouse actions, and keystrokes. A function that intercepts a particular type of event is known as a hook procedure.

For the sake of simplicity, you can think of hooks as Windows’ global events and hook procedures as your event handlers for them. Many might disagree with my analogy and i do agree that its not the best but still, it gets the job done.

Before we can implement a Windows hook, you need to make sure that you have at least some basic understanding of the C++ programming language. If you don’t, i would recommend you go and checkout this free course at the Microsoft Virtual Academy before you continue any further.

How-to implement Windows hook

Now that we have the brief introduction and prerequisites out of our way, we should start with the implementation of hooks using C++. I would be using Microsoft’s Visual Studio 2013 but this code should run in pretty much any C++ IDE. Also, I would only be implementing the WH_KEYBOARD_LL hook through which we can get the low-level keyboard input events. This is mainly due to two reasons:

  • WH_KEYBOARD_LL hook is easy to implement and understand.
  • Other types of hooks have almost a similar implementation.

Start off using an empty console project and add the following lines of code to your Source.cpp file.

We have included iostream and Windows.h files into our program. You probably know what iostream is for,Windows.h file has the code required to install and uninstall a Windows hook. Pragma pre-processor directive tells the compiler that the user32.lib file will be required as well.

While statement on the line #7 puts the program in a message loop and makes sure that the program stays alive. We need this because the hooks are uninstalled once you program exits so without this while statement, our program will immediately close after running.

Now, add the following lines of code just above the declaration of our program’s main method.

First, we declare and initialize a variable of the type HHOOK. This actually is a pointer that gets set once the hook has been installed. MyLowLevelKeyboardProc() is the event handler (or the hook procedure) that runs once the respected Windows’ global event (or hook) is triggered. CallNextHookEx() returns the next hook procedure in the queue, for execution. If you don’t do this, other application’s hook procedures queued after yours won’t work. This might cause other applications to behave irregularly. You can read in more detail aboutLowLevelKeyboardProc() and it’s arguments in the MSDN documentation.

We have done most of the work by now. The basic structure of our  C++ program is ready. We have defined theLowLevelKeyboardProc() hook procedure. Now all that is left is to install the hook so that we can start receiving our low-level keyboard events.

To do that, add the following code just above the while loop, into the main function of your program.

What this does is, it installs our MyLowLevelKeyBoardProc() into the WH_KEYBOARD_LL hook and return a pointer tohHook. If SetWindowsHookEx() fails due to some reason, hHook is null and the error is displayed in the console window.

Your complete program should now look something like this.

That’s it. Run your program (Ctrl + F5), click on the task-bar and press some keys from the keyboard. You’ll should see something like the screenshot below.

hook

In my experience, those are all the basics you need to know about how to implement hooks in C++. Still, if you have any further questions please feel free to ask. I’ll try my level best to answer them.

You can download the final source code from my Codeplex project. Meanwhile, also do checkout some more recommend resources given below.

Reference: http://haseeb-ahmed.com/blog/2015/02/global-windows-hook-in-visual-c/

Hooking

In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a “hook”.

Hooking is used for many purposes, including debugging and extending functionality. Examples might include intercepting keyboard or mouse event messages before they reach an application, or intercepting operating system calls in order to monitor behavior or modify the function of an application or other component. It is also widely used in benchmarking programs, for example frame rate measuring in 3D games, where the output and input is done through hooking.

Hooking can also be used by malicious code. For example, rootkits, pieces of software that try to make themselves invisible by faking the output of API calls that would otherwise reveal their existence, often use hooking techniques. A wallhack is another example of malicious behavior that can stem from hooking techniques. It is done by intercepting function calls in a computer game and altering what is shown to the player to allow them to gain an unfair advantage over other players.

Reference: https://en.wikipedia.org/wiki/Hooking