Processing Global Mouse And Keyboard Hooks in C #

xiaoxiao2021-03-06  82

REL = "stylesheet" type = text / css href = "http://www.codeproject.com/styles/global.css">

Download Source Files - 7.94 KB Download Demo Project - 5.20 KB

Introduction

This class allows you to tap keyboard and mouse and / or to detect their activity even when an application runs in the background or does not have any user interface at all. This class raises common .NET events with KeyEventArgs and MouseEventArgs, so you can easily Retrieve Any Information You NEED.

Background

There are a number of applications that run in background and detect user inactivity to change their mode. For example, MSN Messenger (or any other messenger). I was going to write such an application, so I searched MSDN and found "exactly" what I needed: 318804 - HOW tO: Set a Windows Hook in Visual C # .NET This article describes how to tap the mouse movement, but it was working only when an application was active At the end of this article, I found this explanation.. : "Global Hook Is not Supported in .NET Framework You can not implement global hooks in Microsoft .NET Framework ...." Anyway, I continued my research and found out that there are exceptions there are WH_KEYBOARD_LL and WH_MOUSE_LL hooks that can be.. INSTALLED GLOBALLY. SO I HAVE BASICLY REPLAECED WH_MOUSE to WH_MOUSE_LL IN The MSDN EXAMPLE AND IT WORKED.

............

I found a similar article in CodeProject under Global System Hooks in .NET By Michael Kennedy, but what I dislike there is an unmanaged DLL in C that is a main part of this solution. This unmanaged DLL in C and a number of classes make it Complicated to integrate it in my owna tiny coplication.using the code

To use this class in your application, you need just to create an instance of it and hang on events you would like to process. Hooks are automatically installed when the object created, but you can stop and start listening using appropriate public methods.

UserActivityHook ActHook;

Void MainformLoad (Object Sender, System.EventArgs E)

{

ACTHOOK = New UserActivityHook (); // crate an instance

// Hang on Events

ACTHOK.ONMOUSEACTIVITY = New MouseEventHandler (Mousemoved);

ACTHOK.KEYDOWN = New KeyEventHandler (MykeyDown);

ACTHOK.KEYPRESS = New KeyPressEventHandler (myKeyPress);

ACTHOK.KEYUP = New KeyEventHandler (myKeyup);

}

Now, An Example of How to Process An Event:

Public Void Mousemoved (Object Sender, MouseEventArgs E)

{

LabelmousePosition.text = string.format ("x = {0} y = {1}", E.x, E.Y);

IF (E.CLICKS> 0) Logwrite ("MouseButton -" E.Button.toString ());

}

转载请注明原文地址:https://www.9cbs.com/read-95290.html

New Post(0)