Global System Hooks in. net__.net

Source: Internet
Author: User

Link from:https://www.codeproject.com/articles/6362/global-system-hooks-in-net

A class library for using *global* system hooks. NET. Download Demo project-100 kb Download source-150 kb

Introduction

This article discusses the "use of" global system hooks in. NET applications. A Reusable Class library is developed along the way.

You may have noticed the other articles in using System hooks with P/invoke on Code Project or other publications und section below). This article are similar to those but there is a significant difference. This article covers a using global system hooks in. NET whereas the other articles a local system cover. The ideas are similar but implementation requirements. Background

In case you are are not familiar with the concept of system hooks in Windows, let me state a few brief System Hook allows to insert a callback function which intercepts certain Windows messages (e.g., mouse related Messages). A local system Hook is A system hook that was called only then the specified messages are processed by a single t Hread. A global system Hook is A system hook this is called then the specified messages are processed by any applicatio N on the entire system.

There are several good articles which introduce the concept of system hooks. Rather than rehashing the introductory information here, I'll simply refer readers to those articles for background ation on system hooks. If you are familiar with the concept of system hooks, then you should is able to get everything your need from this article. About hooks[^] in the MSDN Library. Cutting Edge-windows Hooks the. NET Framework [^] by Dino Esposito. Using Hooks from C # [^] by Don Kackman.

What we are going to cover at this article are extending this information to create a global system hooks which can be used By. NET classes. We'll develop a class library in C # and a DLL in unmanaged C + + which together'll accomplish this goal. Using The Code

Before we dig into the developing this library, let's take a quick look at where we are headed. In this article, we'll develop a class library that installs  global  system hooks and exposes The events processed by the hook as a. NET event's our hook class. To illustrate the usage of the system hook classes, we'll create a mouse event hook and keyboard event hook in a Windows Forms application written in C #.

The class library can be used to create any type of system hook. There are two that come pre-built:mousehookand Keyboardhook. We have also included specialized versions of these classes called Mousehookext and Keyboardhookext respectively. Following the model set by those classes, and you can easily build system hooks for any of the "hook event types in the" Win3 2 API. Also, the entire class library comes with a compiled HTML Help file which documents the classes. Be sure to look at the ' Help file ' if you decide to the use this library in your applications.

The usage and lifecycle of the Mousehook class is quite simple. We create an instance of Mousehook class. Hide Copy Code

mouseHook = new MouseHook(); // mouseHook is a member variable

Next, we wire up the MouseEvent event to a class level method. Hide Copy Code

mouseHook.MouseEvent += new MouseHook.MouseEventHandler(mouseHook_MouseEvent);

// ...

private void mouseHook_MouseEvent(MouseEvents mEvent, int x, int y)
{
    string msg = string.Format("Mouse event: {0}: ({1},{2}).", 
                                           mEvent.ToString(), x, y);
    AddText(msg); // Adds the message to the text box.
}

To start receiving mouse events, simply install the hook. Hide Copy Code

mouseHook.InstallHook();

To stop receiving events, simply uninstall the hook. Hide Copy Code

mouseHook.UninstallHook();

You can also call Dispose which'll uninstall the hook as.

It is important This uninstall the hook when your application exits. Leaving system hooks installed'll slow message processing to all applications on the system at best. It could even cause one or more processes to become unstable. To put it in the more technical terms:it ' s really really the bad to forget this part. So, being sure to remove your system hooks is done with them. We ensure that we remove the system hooks in our sample application by adding a dispose of call in the Form ' s Dispose method. Hide Copy Code

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        if (mouseHook != null)
        {
            mouseHook.Dispose();
            mouseHook = null;
        }

        // ...
    }
}

That's all there are to using the class library. It comes with two system hook classes and is easily extendable. Building the Library

The

There are two major components the library. The A C # class library which your use directly in your application. This class library, in turn, uses a unmanaged C + + DLL internally to manage the system hooks directly. We'll be the discuss developing the C + + part. Next, we'll cover how to use this library in C # to build a general hooking class. As we discuss the C + +/C # interaction, we ll pay particular attention to how the C + + methods and data types map to. NET m Ethods and data types.

You are wondering why we need two libraries, especially an unmanaged C + + DLL. You may have noticed also that two of the reference articles mentioned in the background section of this article does not us e any unmanaged code. To this I say, "exactly! That ' s why I ' m writing the This article. When you are about how system hooks actually implement their functionality, it makes sense we need code. In order for a global system hook to work, the Windows inserts your DLL into the process space of every running process. Since most processes are not. NET processes, they cannot execute. NET assemblies. We need an unmanaged code stub which Windows can inserts into all processes that would be hooked.

The ' business is ' to ' provide a mechanism to pass a. NET delegate into our C + + library. Thus, we defined the following function (Setuserhookcallback) and function pointer (HOOKPROC) in C + +. Hide Copy Code

int SetUserHookCallback(HookProc userProc, UINT hookID)
Hide Copy Code
typedef void (CALLBACK *HookProc)(int code, WPARAM w, LPARAM l)

The second parameter to Setuserhookcallback are the type of hook that this function pointer are intended to being used with. Now, we have to define corresponding methods and delegates in C # to use this code. Here are how we map this to C #: Hide Copy Code

private static extern SetCallBackResults 
  SetUserHookCallback(HookProcessedHandler hookCallback, HookTypes hookType)
Hide Copy Code
protected delegate void HookProcessedHandler(int code, 
                                      UIntPtr wparam, IntPtr lparam)
Hide Copy Code
public enum HookTypes
{
   JournalRecord         = 0,
   JournalPlayback       = 1,
   // ...
   KeyboardLL            = 13,
   MouseLL               = 14
};

We import the setuserhookcallback function as a static external method for our abstract base hook CLASS&NB Sp Systemhook using The dllimport attribute. To accomplish this, we have to map some rather foreign data types. We have to create a delegate to serve as our function pointer. This is doing by defining the hookprocesshandler as above. We need a function which in C + + has the signature  (int, WPARAM, LPARAM). In the Visual Studio. NET C + + Compiler, int is the same as in C #. That is, int is int32 in both C + + and C #. This has is not always been the case. Some compilers treat c++ int as int16. We ' re sticking with the Visual Studio. NET C + + compiler for this project, so we won ' t worry about other definitions due to Compiler differences. Finally, we have defined the hooktypes enumeration by explicitly setting the enumeration values to the same Defining the C + + equivalents of the hook Types. These C + + definitions are located in The winuser.h header file.

Next, we need to pass WPARAM and LPARAM values around in C #. These are really pointers to C + + UINT and longvalues respectively. In C # speak, they ' re pointers to uint and int. In case you are not sure what a WPARAM are, can simply look it's up where it's defined by right clicking in the C + + code And choosing "Go To Definition". That's takes to this definition in windef.h. Hide Copy Code

// From windef.h:
typedef UINT_PTR            WPARAM;
typedef LONG_PTR            LPARAM;

Therefore, we chose system.uintptr and System.IntPtr as we variable types for the WPARAM and lparamtypes when they C#.

Now, let's how the hook base class uses these imported methods to pass a callback function (delegate) to C + + which Allows the C + + library to directly call into your system hook class instance. The constructor, The systemhook class creates a delegate to the private method internalhookcallb Ack which matches the hookprocessedhandler delegate signature. Then, it passes this delegate and its 

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.