C#键盘钩子拦截键盘按键
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#键盘钩子,本文以C#语言为例,演示拦截键盘按键。首先打开VS创建一个窗体应用程序。如图:
需要引入以下两个命名空间。
using System.Runtime.InteropServices;
using System.Diagnostics;
以下是全部源码:
using System;
using System.Collections.Generic;
using ponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace WindowsForms5107
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//定¨义?一?个?结á构1
public struct HookStruck
{
public int vkCode;
public int scanCode;
public int time;
}
public delegate int FunctionAddr(int ncode,IntPtr wParam,IntPtr iparam);
[DllImport("user32.dll")]
//参?数簓介é绍Θ?:阰hookID表括?示?参?数簓类え?型í,?有瓺鼠酣?标括?钩3子哩?,?键ü盘ì钩3子哩?等台?类え?型í,?callfunction:阰回?调獭?函ˉ数簓地?址·,?即′你?要癮转羇而?执′行D的?程ì序î地?址·。£
//hInstance:钩3子哩?程ì序î的?实害??柄括?。£threadID线?程ìId,你?要癮监à视酣?的?程ì序î的?iD,当獭纈d=0时骸?,?为a系μ统?钩3子哩?,?监à控?整?个?系μ统?
private static extern int SetWindowsHookEx(int hookID,FunctionAddr callFunction,IntPtr hInstance,int threadId);
[DllImport("kernel32.dll")]
//获?取?应畖用?程ì序î句?柄括?
private static extern IntPtr GetModuleHandle(string name);
[DllImport("user32.dll")]
//钩3子哩?卸?载?
private static extern bool UnhookWindowsHookEx(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
this.InstaHook();
}
IntPtr _hookWindowPtr = IntPtr.Zero;
private void InstaHook()
{
FunctionAddr callbac = new FunctionAddr(CallBackFunction);
string modname = Process.GetCurrentProcess().MainModule.ModuleName;
int WH_HOOKid = 13;
_hookWindowPtr = (IntPtr)GetModuleHandle(modname);
IntPtr hookvalue =
(IntPtr)SetWindowsHookEx(WH_HOOKid,callbac,_hookWindowPtr,0);
}
private int CallBackFunction(int ncode,IntPtr wParam,IntPtr iparam)
{
HookStruck hookstruck = (HookStruck)Marshal.PtrToStructure(iparam,typeof(HookStruck));
//注痢?意癮65,90分?别纄是?A,?Z的?ASCII码?,?即′当獭?检ì测a按恪?下?A-Z时骸?,?执′行D拦?截?操ù作痢?
if(hookstruck.vkCode>=65&&hookstruck.vkCode<=122)
{
this.textBox1.Text = "按恪?键ü" + (char)hookstruck.vkCode + "已?拦?截?";
}
return 0;
}
private void button2_Click(object sender, EventArgs e)
{
//钩3子哩?卸?载?
bool result = true;
IntPtr hooxUn = (IntPtr)GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
if (hooxUn != IntPtr.Zero)
{
result = (UnhookWindowsHookEx(_hookWindowPtr)&&result);