General mouse and keyboard hook. Image hijacking. auto start upon startup, mouse and keyboard hook

Source: Internet
Author: User

General mouse and keyboard hook. Image hijacking. auto start upon startup, mouse and keyboard hook

Using System;
Using System. Collections. Generic;
Using System. IO;
Using System. Windows. Forms;
Using System. Runtime. InteropServices;
Using System. Reflection;


Namespace HookTest
{
/*
Note:
If the returned value of SetWindowsHookEx is 0 during running, this is because of the. net debugging mode. The specific method is to disable the host process and open the project in Visual Studio.
Click properties on the project menu ".
Click the debug tab.
Clear the Enable Visual Studio host process (enable windows host process) check box or check enable unmanaged code debugging.
*/

// Declare wrapper managed POINT class.
[StructLayout (LayoutKind. Sequential)]
Public class POINT
{
Public int x;
Public int y;
}
// Declare wrapper managed MouseHookStruct class.
[StructLayout (LayoutKind. Sequential)]
Public class MouseHookStruct
{
Public POINT pt;
Public int hwnd;
Public int wHitTestCode;
Public int dwExtraInfo;
}
// Declare wrapper managed KeyboardHookStruct class.

[StructLayout (LayoutKind. Sequential)]
Public class 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.
}


Public class GlobalHook
{
Public delegate int HookProc (int nCode, Int32 wParam, IntPtr lParam );
Public delegate int GlobalHookProc (int nCode, Int32 wParam, IntPtr lParam );
Public GlobalHook ()
{
// Start ();
}
~ GlobalHook ()
{
Stop ();
}
Public event MouseEventHandler OnMouseActivity;
Public event KeyEventHandler KeyDown;
Public event KeyPressEventHandler KeyPress;
Public event KeyEventHandler KeyUp;

/// <Summary>
/// Define the mouse hook handle.
/// </Summary>
Static int _ hMouseHook = 0;
/// <Summary>
/// Define the keyboard hook handle
/// </Summary>
Static int _ hKeyboardHook = 0;

Public int HMouseHook
{
Get {return _ hMouseHook ;}
}
Public int HKeyboardHook
{
Get {return _ hKeyboardHook ;}
}

/// <Summary>
/// Mouse hook constant (from Microsoft SDK Winuser. h)
/// </Summary>
Public const int WH_MOUSE_LL = 14;
/// <Summary>
/// Keyboard hook constant (from Microsoft SDK Winuser. h)
/// </Summary>
Public const int WH_KEYBOARD_LL = 13;

/// <Summary>
/// Define the delegate object of the mouse processing process
/// </Summary>
GlobalHookProc MouseHookProcedure;
/// <Summary>
/// Delegate object of the keyboard processing process
/// </Summary>
GlobalHookProc KeyboardHookProcedure;

// Import window hook Extension Method Import

/// <Summary>
/// Hook Installation Method
/// </Summary>
[DllImport ("user32.dll", CharSet = CharSet. Auto, CallingConvention = CallingConvention. StdCall)]
Public static extern int SetWindowsHookEx (int idHook, GlobalHookProc lpfn, IntPtr hInstance, int threadId );

/// <Summary>
/// Uninstall the hook
/// </Summary>
[DllImport ("user32.dll", CharSet = CharSet. Auto, CallingConvention = CallingConvention. StdCall)]
Public static extern bool UnhookWindowsHookEx (int idHook );

// Import for CallNextHookEx.
/// <Summary>
/// Use this function to pass the hook information to the next hook process in the chain.
/// </Summary>
[DllImport ("user32.dll", CharSet = CharSet. Auto, CallingConvention = CallingConvention. StdCall)]
Public static extern int CallNextHookEx (int idHook, int nCode, Int32 wParam, IntPtr lParam );

Public bool Start ()
{
// Install Mouse hook
If (_ hMouseHook = 0)
{
// Create an instance of HookProc.
MouseHookProcedure = new GlobalHookProc (MouseHookProc );
Try
{
_ HMouseHook = SetWindowsHookEx (WH_MOUSE_LL,
MouseHookProcedure,
Marshal. GetHINSTANCE (
Assembly. GetExecutingAssembly (). GetModules () [0]),
0 );
}
Catch (Exception err)
{}
// If the installation of the mouse hook fails
If (_ hMouseHook = 0)
{
Stop ();
Return false;
// Throw new Exception ("SetWindowsHookEx failed .");
}
}
// Install the keyboard hook
If (_ hKeyboardHook = 0)
{
KeyboardHookProcedure = new GlobalHookProc (KeyboardHookProc );
Try
{
_ HKeyboardHook = SetWindowsHookEx (WH_KEYBOARD_LL,
KeyboardHookProcedure,
Marshal. GetHINSTANCE (
Assembly. GetExecutingAssembly (). GetModules () [0]),
0 );
}
Catch (Exception err2)
{}
// If keyboard hook installation fails
If (_ hKeyboardHook = 0)
{
Stop ();
Return false;
// Throw new Exception ("SetWindowsHookEx ist failed .");
}
}
Return true;
}

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 ist failed .");
}

}
/// <Summary>
/// Uninstall the hook. If the process ends forcibly, record the id of the last hook and uninstall it based on the hook id.
/// </Summary>
Public void Stop (int hMouseHook, int hKeyboardHook)
{
If (hMouseHook! = 0)
{
UnhookWindowsHookEx (hMouseHook );
}
If (hKeyboardHook! = 0)
{
UnhookWindowsHookEx (hKeyboardHook );
}
}

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 (nCode> = 0) & (OnMouseActivity! = Null ))
{
MouseButtons button = MouseButtons. None;
Switch (wParam)
{
Case WM_LBUTTONDOWN: // press the left button
// Case WM_LBUTTONUP: // right-click and press
// Case WM_LBUTTONDBLCLK: // Press
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 the specified virtual-key code and keyboard state to the corresponding character or characters. the 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 pressed ).
Byte [] lpbKeyState, // [in] Pointer to a 256-byte array that contains the current keyboard state. each element (byte) in the array contains the state of one key. if the high-order bit of a byte is set, the key is down (pressed ). the low bit, if set, indicates that the key is toggled on. in this function, 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 contains es 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 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 [] keyState = 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 );
}
}
}

A hook is a listener for message queues.

The above is the source code of the conventional mouse and keyboard hook. MSAA is required for listening to the button clicking of an external program, as mentioned in my previous WindowAPI.

 

Public static void WriteReg (string keyname, string keyvalue)
{
Try
{


Registry. SetValue (@ "HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ Image File Execution Options" + keyname, "Debugger", keyvalue );
}

Catch (SecurityException se)
{
Console. WriteLine (se. Message );
}
Catch (UnauthorizedAccessException uae)
{
Console. WriteLine (uae. Message );
}
}

WriteReg ("calc.exe", @ "c: \ windows \ system32 \ cmd.exe ");

The Registry path is the win debugging path.

If the calculator is written as a key, the command line is written as a value, the command line is started when the calculator is started, and the calculator is not started. If the DLL of the command line is deleted, the calculator cannot be started.

Modify the command line name to remove the image hijacking.

Private static void button2_Click ()

{// Set the self-starting Program


Try

{

String FileName = @ "D: \ work \ enterprise template \ jinqiu \ dianji test \ ConsoleApplication1 \ dianjidata \ bin \ Debug \ dianjidata.exe ";

String parameter filename = "dianjidata.exe ";

// Open the subkey Node

RegistryKey MyReg = Registry. LocalMachine. OpenSubKey ("SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Run", true );

If (MyReg = null)

{// If the child key node does not exist, create it

MyReg = Registry. LocalMachine. CreateSubKey ("SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Run ");

}

// Set the auto-Start Program in the Registry

MyReg. SetValue (optional FileName, FileName );

MessageBox. Show ("the operation on the self-starting program is successfully set! "," Message prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );

}

Catch (Exception Err)

{

MessageBox. Show ("An error occurred while writing the registry! "," Message prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );

}

}

Auto-start

 

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.