C#钩子屏蔽键盘鼠标
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//屏蔽键盘
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
namespace KeyboardDLL
{
public class KeyboardHook
{
public delegate int KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
static int hKeyboardHook = 0;
KeyboardProc KeyboardHookProcedure;
///
///钩子函数,需要引用空间(using System.Reflection;)
///线程钩子监听键盘消息设为2,全局钩子监听键盘消息设为13
///线程钩子监听鼠标消息设为7,全局钩子监听鼠标消息设为14
///
public const int WH_KEYBOARD = 13;
public const int WH_MOUSE_LL = 14;
public struct KeyboardMSG
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
public int VK_CONTROL;
public int VK_MENU;
public int VK_DELETE;
}
///
/// kernel32.dll是Windows 95,Windows 98和Windows Me中使用的32位动态链接库文件。
///kernel32.dll是负责内存管理、输入输出以及中断等工作。启动Windows 系统之后,
///kernel32.dll就会被装载到不会被其他应用程序影响的受保护的内存空间中。在某些时候,
///会出现invalid page fault(IPF)错误信息,这是由于其他应用程序视图访问kernel32.dll
///所在的受保护内存空间引起的。不过有时,特定的某些程序也能引起这种错误。
///
///
[DllImport("kernel32")]
public static extern int GetCurrentThreadId();
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, KeyboardProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
private int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
KeyboardMSG m = (KeyboardMSG)Marshal.PtrToStructure(lParam, typeof(KeyboardMSG));
if((int)m.vkCode == 91|| (int)m.vkCode == 92 ||(int)m.vkCode == 10)
{
return1;
}
if(((int)m.vkCode == 46) && ((int)m.vkCode == 17) && ((int)m.vkCode == 18))
{
return2;
}
if ((int)m.vkCode == 20)
{
return1;
}
if (1 == 1)
{
return1;
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
// 安装钩子
public void KeyMaskStart()
{
if (hKeyboardHook == 0)
{
// 创建HookProc实例
KeyboardHookProcedure = new KeyboardProc(KeyboardHookProc);
// 设置线程钩子
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardHookProcedure,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules() [0]), 0);
// 如果设置钩子失败
if (hKeyboardHook == 0)
{
KeyMaskStop();
throw new Exception("SetWindowsHookEx failed."); }
}
}
// 卸载钩子
public void KeyMaskStop()
{
bool retKeyboard = true;
if (hKeyboardHook != 0)
{
retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
}
if (!(retKeyboard))
{
throw new Exception("UnhookWindowsHookEx failed.");