常规鼠标键盘钩子.映像劫持.开机自启动

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

namespace HookTest
{
/*
注意:
如果运行中出现SetWindowsHookEx的返回值为0,这是因为.net 调试模式的问题,具体的做法是禁用宿主进程,在 Visual Studio 中打开项目。
在“项目”菜单上单击“属性”。
单击“调试”选项卡。
清除“启用 Visual Studio 宿主进程(启用windows承载进程)”复选框 或 勾选启用非托管代码调试
*/

//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>
/// 定义鼠标钩子句柄.
/// </summary>
static int _hMouseHook = 0;
/// <summary>
/// 定义键盘钩子句柄
/// </summary>
static int _hKeyboardHook = 0;

public int HMouseHook
{
get { return _hMouseHook; }
}
public int HKeyboardHook
{
get { return _hKeyboardHook; }
}

/// <summary>
/// 鼠标钩子常量(from Microsoft SDK Winuser.h )
/// </summary>
public const int WH_MOUSE_LL = 14;
/// <summary>
/// 键盘钩子常量(from Microsoft SDK Winuser.h )
/// </summary>
public const int WH_KEYBOARD_LL = 13;

/// <summary>
/// 定义鼠标处理过程的委托对象
/// </summary>
GlobalHookProc MouseHookProcedure;
/// <summary>
/// 键盘处理过程的委托对象
/// </summary>
GlobalHookProc KeyboardHookProcedure;

//导入window 钩子扩展方法导入

/// <summary>
/// 安装钩子方法
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, GlobalHookProc lpfn,IntPtr hInstance, int threadId);

/// <summary>
/// 卸载钩子方法
/// </summary>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);

//Import for CallNextHookEx.
/// <summary>
/// 使用这个函数钩信息传递给链中的下一个钩子过程。
/// </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 (_hMouseHook == 0)
{
Stop();
return false;
//throw new Exception("SetWindowsHookEx failed.");
}
}
//安装键盘钩子
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 (_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>
/// 卸载hook,如果进程强制结束,记录上次钩子id,并把根据钩子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: //左键按下
//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 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 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 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);
}
}
}

钩子是对消息队列的监听.

以上就是常规鼠标键盘钩子的源码.还有一个对外部程序按钮点击的监听需要MSAA.在我之前的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");

注册表所在的路径是win调试路径.

如果把计算器写成键.命令行写成值.那么在计算器启动的时候.会启动命令行.而不会启动计算器.如果命令行的DLL被删除.计算器无法启动.

修改命令行的名称就可以解除镜像劫持.

private static void button2_Click()

{//设置自启动程序

try

{

string FileName = @"D:\工作\企业模版\金丘\dianji test\ConsoleApplication1\dianjidata\bin\Debug\dianjidata.exe";

string ShortFileName = "dianjidata.exe";

//打开子键节点

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

if (MyReg == null)

{//如果子键节点不存在,则创建之

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

}

//在注册表中设置自启动程序

MyReg.SetValue(ShortFileName, FileName);

MessageBox.Show("设置自启动程序操作成功!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

catch (Exception Err)

{

MessageBox.Show("写注册表操作发生错误!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

}

开机自启动

时间: 2024-10-01 10:58:25

常规鼠标键盘钩子.映像劫持.开机自启动的相关文章

C#鼠标键盘钩子

using System;using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace ICS.Common { /// <summary> /// 这个类可以让你得到一个在运行中程序的所有键盘或鼠标事件 /// 并且引发一个带KeyEventArgs

C#键盘钩子 鼠标钩子

最新对C#模拟键盘按键,鼠标操作产生了兴趣.特从网上收集了一些常用的API用来调用键盘,鼠标操作. class Win32API { #region DLL导入 /// <summary> /// 用于设置窗口 /// </summary> /// <param name="hWnd"></param> /// <param name="hWndInsertAfter"></param> ///

C#实现键盘钩子

前言: 因为项目中需要使用到快捷键,所以上网找资料了解关于快捷键的实现技术,于是有了键盘钩子的使用学习.在网上了解到,键盘钩子其实只是很多种钩子中的其中一种.所谓钩子:请看下面关于钩子的描述(来自百度百科): Windows系统是建立在事件驱动的机制上的,说穿了就是整个系统都是通过消息的传递来实现的.而钩子是Windows系统中非常重要的系统接口,用它可以截获并处理送给其他应用程序的消息,来完成普通应用程序难以实现的功能. 钩子可以监视系统或进程中的各种事件消息,截获发往目标窗口的消息并进行处理

键盘钩子 用来截屏

.点击开始按钮 .a窗体隐藏,b窗体显示 scsysrq截图 .需要在桌面创建bc文件夹. 总的思路就是用钩子获取键盘信息 然后进行截图的线程控制 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.Drawing;using System.Linq;using System.Runtime

C#全局鼠标键盘Hook

原文出自:http://www.cnblogs.com/iEgrhn/archive/2008/02/17/1071392.html using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace DCIEngine.Frame

钩子编程(HOOK) 安装进程内键盘钩子 (1)

摘要:钩子能够监视系统或进程中的各种事件消息.截获发往目标窗体的消息并进行处理.这样,我们就能够在系统中安装自己定义的钩子,监视系统中特定事件的发生.完毕特定的功能,比方截获键盘.鼠标的输入.屏幕取词,日志监视等等. 以下演示怎样安装进程内键盘钩子, Step 1:打开VC6.0.创建一个基于对话框的MFC应用程序. Step 2:在BOOL CHookDlg::OnInitDialog()函数上面编写例如以下代码:(注意是在上面编写.不是在OnInitDialog()里面) HHOOK g_h

模拟鼠标键盘操作,含硬件模拟技术[转载]

键盘是我们使用计算机的一个很重要的输入设备了,即使在鼠标大行其道的今天,很多程序依然离不开键盘来操作.但是有时候,一些重复性的,很繁琐的键盘操作总会让人疲惫,于是就有了用程序来代替人们按键的方法,这样可以把很多重复性的键盘操作交给程序来模拟,省了很多精力,按键精灵就是这样的一个软件.那么我们怎样才能用VB来写一个程序,达到与按键精灵类似的功能呢?那就让我们来先了解一下windows中响应键盘事件的机制.    当用户按下键盘上的一个键时,键盘内的芯片会检测到这个动作,并把这个信号传送到计算机.如

钩子编程(HOOK) 安装进程内键盘钩子

作者 : 卿笃军 系统钩子:钩子可以监视系统或进程中的各种事件消息,截获发往目标窗口的消息并进行处理.这样,我们就可以在系统中安装自定义的钩子,监视系统中特定事件的发生,完成特定的功能,比如截获键盘.鼠标的输入,屏幕取词,日志监视等等. 下面演示如何安装进程内键盘钩子: 第一步:打开VC6.0,创建一个基于对话框的MFC应用程序. 第二步:在BOOL CHookDlg::OnInitDialog()函数上面编写如下代码:(注意是在上面编写,不是在OnInitDialog()里面) HHOOK g

一个简单的键盘钩子程序

实现适时监视键盘,并将按键信息保存在TXT文件中的程序       Windows系统是建立在事件驱动的机制上的,说穿了就是整个系统都是通过消息的传递来实现的.而钩子是Windows系统中非常重要的系统接口,用它可以截获并处理送给其他应用程序的消息,来完成普通应用程序难以实现的功能.钩子的种类很多,每种钩子可以截获并处理相应的消息,如键盘钩子可以截获键盘消息,外壳钩子可以截取.启动和关闭应用程序的消息等.本文在VC6编程环境下实现了一个简单的键盘钩子程序,并对Win32全局钩子的运行机制.Win