寻求一个C#+低级Windows API钩子拦截键盘输入的完整例子,网上的只是一些简单步骤,本人愚钝,不会实现

有的话,发我邮箱 nmzxmmw@yahoo.com.cn 谢谢!!!
2024-12-29 05:51:00
推荐回答(1个)
回答1:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Diagnostics; namespace Ts002 { public class MyAPI { #region struct [StructLayout(LayoutKind.Sequential)] public struct KeyBoardHookStruct { public int vkCode; public int scanCode; public int flags; public int time; public int dwExtraInfo; } #endregion [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowsHookEx( int idHook, HookProc 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 ); [DllImport("kernel32.dll")] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("user32.dll")] public static extern IntPtr FindWindow( string lpClassName, string lpWindowName); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern void keybd_event( byte bVk, byte bScan, Int32 dwFlags, Int32 dwExtraInfo); private const int KEYEVENTF_KEYUP = 2; public delegate int HookProc(int nCode,IntPtr wParam,IntPtr lParam); private static int hHook; private static HookProc KeyBoardHookProcedure; public static IntPtr hwnd;//你要截获的窗口的句柄 public void Hook_Start() { // 安装键盘钩子 if (hHook == 0) { KeyBoardHookProcedure = new HookProc(KeyBoardHookProc); hHook = SetWindowsHookEx(13, KeyBoardHookProcedure, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0); } } public void Hook_Clear() { bool flag = true; if (hHook != 0) { flag = UnhookWindowsHookEx(hHook); hHook = 0; } if (!flag) { throw new Exception("UnhookWindowsHookEx failed."); } } public static int KeyBoardHookProc(int nCode, IntPtr wParam, IntPtr lParam) { //监控用户键盘输入 IntPtr prt; KeyBoardHookStruct input = (KeyBoardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyBoardHookStruct)); //截获Q 键 if (input.vkCode == (int)Keys.Q) { //截获后你想要做的事情 prt = hwnd;//窗口句柄 if(prt!=IntPtr.Zero) { SetForegroundWindow(prt); keybd_event((byte)Keys.U, 0, 0, 0); //keybd_event((byte)Keys.U, 0, KEYEVENTF_KEYUP, 0); keybd_event((byte)Keys.I, 0, 0, 0); //keybd_event((byte)Keys.I, 0, KEYEVENTF_KEYUP, 0); } return 1; } // 继续执行下一个钩子程序 return CallNextHookEx(hHook, nCode, wParam, lParam); } } } 我测试截获一个txt的文本程序,没有问题,其他的没有测试过.

希望采纳