16,554
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Runtime.InteropServices;
namespace Hook
{
/// <summary>
/// 设置键盘钩子屏蔽win键
/// </summary>
public class Win32Hook
{
public Win32Hook()
{
}
private IntPtr hHook =IntPtr.Zero;
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public const int WH_KEYBOARD = 13;
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern int CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[StructLayout(LayoutKind.Sequential)]
public struct KBDLLHOOKSTRUCT
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
private int KeyBoardHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
KBDLLHOOKSTRUCT kb = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
else
{
if (kb.vkCode != 91)
return CallNextHookEx(hHook, nCode, wParam, lParam); //不等于win键时
else
return 1;//等于win键时吃掉键盘消息
}
}
//设置Hook
public bool Hook()
{
if (hHook == IntPtr.Zero)
{
HookProc KeyBoardHookProcedure = new HookProc(KeyBoardHookProc);
hHook = SetWindowsHookEx(WH_KEYBOARD, KeyBoardHookProcedure, GetModuleHandle("Hook.dll") ,0);
if(hHook == IntPtr.Zero)
return false;
else
return true;
}
else
return true;
}
//取消Hook
public bool UnHook()
{
if (hHook != IntPtr.Zero)
{
bool ret = UnhookWindowsHookEx(hHook);
hHook = IntPtr.Zero ;
return ret;
}
else
return true;
}
}
}