C # Use global hooks

Source: Internet
Author: User

Transferred from:

Http://topic.csdn.net/u/20080328/07/e0343ac4-32eb-4d7b-acee-c479cf26560a.html

 

Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. reflection;
Using system. runtime. interopservices;
Using system. Windows. forms;

Namespace wa_hooktest
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Internal Enum hooktype // enumeration, hook type
{

// Msgfilter =-1,

// Journalrecord = 0,

// Journalplayback = 1,

Keyboard = 2,

// Getmessage = 3,

// CALLWNDPROC = 4,

// CBT = 5,

// Sysmsgfilter = 6,

// Mouse = 7,

// Hardware = 8,

// DEBUG = 9,

// Shell = 10,

// Foregroundidle = 11,

// Callwndprocret = 12,

Keyboardll = 13,

// Mousell = 14,

};

[Dllimport ("kernel32.dll")]
Static extern int getcurrentthreadid (); // obtain the ID of the current thread

[Dllimport ("user32.dll")]
Internal extern static void unhookwindowshookex (intptr handle); // cancel the HOOK API

[Dllimport ("user32.dll")]
Internal extern static intptr setwindowshookex (INT idhook, [financialas (unmanagedtype. functionptr)] hookproc lpfn, intptr hinstance, int threadid); // sets the HOOK API

[Dllimport ("user32.dll")]
Internal extern static intptr callnexthookex (intptr handle, int code, intptr wparam, intptr lparam); // obtain the next HOOK API
Intptr _ nexthookptr; // record the hook number

Public Delegate intptr hookproc (INT code, intptr wparam, intptr lparam );
Public intptr myhookproc (INT code, intptr wparam, intptr lparam)
{
If (Code <0)
{
Return callnexthookex (_ nexthookptr, code, wparam, lparam );
} // Return, let the subsequent program process the message

If (wparam. toint32 () = 98 | wparam. toint32 () = 66)
{// If the user inputs B

This. textbox1.text = "";
Return (intptr) 1; // The message is returned directly, and the processing is complete.
}
Else
{
Return intptr. Zero; // return, let the subsequent program process the message
}

// If (wparam. toint32 () = 91)
//{
// Return (intptr) 1;
//}
// Else {
// Return intptr. zero;
//}
}

Public void sethook ()
{

If (_ nexthookptr! = Intptr. Zero) // already checked

Return;
// Thread hook
Hookproc myhookproc = new hookproc (myhookproc); // declare a delegate object of your own hook implementation function

// _ Nexthookptr = setwindowshookex (INT) hooktype. keyboard, myhookproc, intptr. Zero, getcurrentthreadid (); // Add it to the hook chain

// Global hook
_ Nexthookptr = setwindowshookex (INT) hooktype. keyboardll, myhookproc, Marshal. gethinstance (assembly. getexecutingassembly (). getmodules () [0]), 0); // Add it to the hook chain

MessageBox. Show (_ nexthookptr. tostring ());
}

Public void unhook ()
{

If (_ nexthookptr! = Intptr. Zero)
{
Unhookwindowshookex (_ nexthookptr); // cancel from the hook chain
_ Nexthookptr = intptr. zero;
}

}

Private void form1_load (Object sender, eventargs E)
{
Sethook ();
}

Private void form=formclosing (Object sender, formclosingeventargs E)
{
Unhook ();
}
}
}

The above procedures do not get hooks. The following are corrected:
 
Problem points:50 Replies:5
Show all repliesShow star repliesShow landlord reply

Modify, delete, report, reference, and reply

Posted on:2008-03-28 09:58:531Floor score:50
There are many similar problems. If you don't want to explain any problem, just send the code...
Create a form4 form. Add two buttons and add events .. Then copy the code
In fact, the difference is the red area.
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;
Using system. runtime. interopservices;
Using system. reflection;
Using system. diagnostics;

Namespace windowsapplication1
{
/// <Summary>
/// Description of mainform.
/// </Summary>
Public partial class form4: Form
{
// Delegate
Public Delegate int hookproc (INT ncode, int wparam, intptr lparam );
Static int hhook = 0;
Public const int wh_keyboard_ll = 13;
// The lowlevel keyboard is intercepted. If it is wh_keyboard = 2, it cannot intercept the system keyboard. Acrobat Reader will obtain the keyboard before you intercept it.
Hookproc keyboardhookprocedure;
// Keyboard hook Structure Function
[Structlayout (layoutkind. Sequential)]
Public class keyboardhookstruct
{
Public int vkcode;
Public int scancode;
Public int flags;
Public int time;
Public int dwextrainfo;
}
# Region dllimport
// Set the hook
[Dllimport ("user32.dll")]
Public static extern int setwindowshookex (INT idhook, hookproc lpfn, intptr hinstance, int threadid );
[Dllimport ("user32.dll", charset = charset. Auto, callingconvention = callingconvention. stdcall)]
// Remove the hook
Public static extern bool unhookwindowshookex (INT idhook );
[Dllimport ("user32.dll")]
// Call the next hook
Public static extern int callnexthookex (INT idhook, int ncode, int wparam, intptr lparam );

[Dllimport ("kernel32.dll")]
Public static extern int getcurrentthreadid ();

[Dllimport ("kernel32.dll")]
Public static extern intptr getmodulehandle (string name );

# Endregion
# Region custom events
Public void hook_start ()
{
// Install the keyboard hook
If (hhook = 0)
{
Keyboardhookprocedure = new hookproc (keyboardhookproc );

// Hhook = setwindowshookex (2,
// Keyboardhookprocedure,
// Getmodulehandle (process. getcurrentprocess (). mainmodule. modulename), getcurrentthreadid ());

Hhook = setwindowshookex (wh_keyboard_ll,
Keyboardhookprocedure,
Getmodulehandle (process. getcurrentprocess (). mainmodule. modulename), 0 );
// If the hook fails to be set.
If (hhook = 0)
{
Hook_clear ();
// Throw new exception ("hook setting failed! ");
}
}
}

// Cancel the hook event
Public void hook_clear ()
{
Bool retkeyboard = true;
If (hhook! = 0)
{
Retkeyboard = unhookwindowshookex (hhook );
Hhook = 0;
}
// If you fail to remove the hook.
If (! Retkeyboard) throw new exception ("unhookwindowshookex failed .");
}

// Add the desired information here
Public static int keyboardhookproc (INT ncode, int wparam, intptr lparam)
{
If (ncode> = 0)
{

Keyboardhookstruct KBH = (keyboardhookstruct) Marshal. ptrtostructure (lparam, typeof (keyboardhookstruct ));
If (KBH. vkcode = (INT) keys. S & (INT) control. modifierkeys = (INT) keys. Control) // intercept F8
{
MessageBox. Show ("the shortcut key has been intercepted! Cannot be saved! ");
Return 1;

}
If (KBH. vkcode = (INT) keys. Y
& (INT) control. modifierkeys = (INT) keys. Control + (INT) keys. alt) // CTRL + ALT + Y
{

// MessageBox. Show ("cannot be saved all! ");
Return 1;
}
If (KBH. vkcode = (INT) keys. X)
{
MessageBox. Show ("cannot be saved all! ");
Return 1;
}
}
Return callnexthookex (hhook, ncode, wparam, lparam );
}
# Endregion

Public form4 ()
{

Initializecomponent ();
}
Private void button#click (Object sender, eventargs E)
{
Hook_start ();
}

Private void button2_click (Object sender, eventargs E)
{
Hook_clear ();
}

}
}

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.