C#键盘屏蔽技术
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
对于键盘钩子,钩子类型为WH_KEYBOARD_LL=13,只需要设置SetWindow sHookEx的idHook参数为13即可“钩”到键盘消息。
关于钩子的类型可以在MSDN上查找,本段代码本人亲测有效。
详细内容如下。
上图是窗体主界面,放置两个button按钮,一个用来开启钩子,一个用来关闭钩子。
后台代码如下
using System;
using System.Collections.Generic;
using ponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace键û盘ì钩3子哩?315
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private IntPtr pKeyboardHook=IntPtr.Zero;
public delegate int HookProc(int nCode,Int32 wParm,IntPtr lParam);
private HookProc KeyboardHookProcedure;
public const int idHOOK=13; //表括?示?钩3子哩?的?类え?型í为a键û盘ì钩3子哩?
[DllImport("user32.dll",CallingConvention=CallingConvention.StdCall)] public static extern IntPtr SetWindowsHookEx(int idHook,HookProc lpfn,IntPtr pinstance,int threadid); //安?装痢?钩3子哩?
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)] public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle); //抽é调獭?一?个?钩3子哩?
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string name); //获?取?系μ统?进?程ì
private void button1_Click(object sender, EventArgs e)
{
InsertHook(); //单蹋?击÷调獭?用?
}
public bool InsertHook() //安?装痢?钩3子哩?
{
IntPtr pin =
(IntPtr)GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
if(this.pKeyboardHook==IntPtr.Zero)
{
this.KeyboardHookProcedure = new HookProc(KeyBoardHookProc);
this.pKeyboardHook =
SetWindowsHookEx(idHOOK,KeyboardHookProcedure,pin,0);
if(this.pKeyboardHook==IntPtr.Zero)
{
UnInsertHook();
return false;
}
}
return true;
}
public bool UnInsertHook() //卸?载?钩3子哩?
{
bool result = true;
if(this.pKeyboardHook!=IntPtr.Zero)
{
result = (UnhookWindowsHookEx(this.pKeyboardHook) && result);
this.pKeyboardHook = IntPtr.Zero;
}
return result;
}
public int KeyBoardHookProc(int ncode, Int32 wpara, IntPtr lparam) //对??屏á蔽?掉?的?热è?键û的?主÷要癮操ù作痢?都?是?放?在ú这a里?面??成é的?,?大洙?家î可é以?灵ⅷ?活?应畖用?这a段?代洙?码?
{
KeyMsg m = (KeyMsg)Marshal.PtrToStructure(lparam, typeof(KeyMsg));
if (pKeyboardHook != IntPtr.Zero)
{
switch ((Keys)m.vkCode)
{
case Keys.LWin: //屏á蔽?左哩甒IN
case Keys.RWin: //屏á蔽?in
case Keys.Delete: //屏á蔽?删?除y键ûdelete
case Keys.Alt: //屏á蔽?Alt
case Keys.Escape: //屏á蔽?Esc
case Keys.F4:
case Keys.Control:
case Keys.Tab:
case Keys.A:
return 1;
}
}
return 0;
}
///<summary>
///声Θ?明÷键û盘ì钩3子哩?的?1类え?型í
///</summary>
[StructLayout(LayoutKind.Sequential)]
private struct KeyMsg
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtrainfo;
}
private void button2_Click(object sender, EventArgs e) {
UnInsertHook();
}
}
}。