黑客来了。。。键盘钩子,听起来很高端。

首先是这个公共的类:globalKeyboardHook.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Utilities {
    /// <summary>
    /// A class that manages a global low level keyboard hook
    /// </summary>
    class globalKeyboardHook {
        #region Constant, Structure and Delegate Definitions
        /// <summary>
        /// defines the callback type for the hook
        /// </summary>
        public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);

        public struct keyboardHookStruct {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }

        const int WH_KEYBOARD_LL = 13;
        const int WM_KEYDOWN = 0x100;
        const int WM_KEYUP = 0x101;
        const int WM_SYSKEYDOWN = 0x104;
        const int WM_SYSKEYUP = 0x105;
        #endregion

        #region Instance Variables
        /// <summary>
        /// The collections of keys to watch for
        /// </summary>
        public List<Keys> HookedKeys = new List<Keys>();
        /// <summary>
        /// Handle to the hook, need this to unhook and call the next hook
        /// </summary>
        IntPtr hhook = IntPtr.Zero;
        #endregion

        #region Events
        /// <summary>
        /// Occurs when one of the hooked keys is pressed
        /// </summary>
        public event KeyEventHandler KeyDown;
        /// <summary>
        /// Occurs when one of the hooked keys is released
        /// </summary>
        public event KeyEventHandler KeyUp;
        #endregion

        #region Constructors and Destructors
        /// <summary>
        /// Initializes a new instance of the <see cref="globalKeyboardHook"/> class and installs the keyboard hook.
        /// </summary>
        public globalKeyboardHook() {
            hook();
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="globalKeyboardHook"/> is reclaimed by garbage collection and uninstalls the keyboard hook.
        /// </summary>
        ~globalKeyboardHook() {
            unhook();
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Installs the global hook
        /// </summary>
        public void hook() {
            IntPtr hInstance = LoadLibrary("User32");
            hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);
        }

        /// <summary>
        /// Uninstalls the global hook
        /// </summary>
        public void unhook() {
            UnhookWindowsHookEx(hhook);
        }

        /// <summary>
        /// The callback for the keyboard hook
        /// </summary>
        /// <param name="code">The hook code, if it isn‘t >= 0, the function shouldn‘t do anyting</param>
        /// <param name="wParam">The event type</param>
        /// <param name="lParam">The keyhook event information</param>
        /// <returns></returns>
        public int hookProc(int code, int wParam, ref keyboardHookStruct lParam) {
            if (code >= 0) {
                Keys key = (Keys)lParam.vkCode;
                if (HookedKeys.Contains(key)) {
                    KeyEventArgs kea = new KeyEventArgs(key);
                    if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null)) {
                        KeyDown(this, kea) ;
                    } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null)) {
                        KeyUp(this, kea);
                    }
                    if (kea.Handled)
                        return 1;
                }
            }
            return CallNextHookEx(hhook, code, wParam, ref lParam);
        }
        #endregion

        #region DLL imports
        /// <summary>
        /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
        /// </summary>
        /// <param name="idHook">The id of the event you want to hook</param>
        /// <param name="callback">The callback.</param>
        /// <param name="hInstance">The handle you want to attach the event to, can be null</param>
        /// <param name="threadId">The thread you want to attach the event to, can be null</param>
        /// <returns>a handle to the desired hook</returns>
        [DllImport("user32.dll")]
        static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);

        /// <summary>
        /// Unhooks the windows hook.
        /// </summary>
        /// <param name="hInstance">The hook handle that was returned from SetWindowsHookEx</param>
        /// <returns>True if successful, false otherwise</returns>
        [DllImport("user32.dll")]
        static extern bool UnhookWindowsHookEx(IntPtr hInstance);

        /// <summary>
        /// Calls the next hook.
        /// </summary>
        /// <param name="idHook">The hook id</param>
        /// <param name="nCode">The hook code</param>
        /// <param name="wParam">The wparam.</param>
        /// <param name="lParam">The lparam.</param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);

        /// <summary>
        /// Loads the library.
        /// </summary>
        /// <param name="lpFileName">Name of the library</param>
        /// <returns>A handle to the library</returns>
        [DllImport("kernel32.dll")]
        static extern IntPtr LoadLibrary(string lpFileName);
        #endregion
    }
}

调用方式:

public partial class Form1 : Form {
        globalKeyboardHook gkh = new globalKeyboardHook();

        public Form1() {
            InitializeComponent();
        }
        [DllImport("user32.dll")]
        public static extern int FindWindow(
            string lpClassName, // class name
            string lpWindowName // window name
        );

        [DllImport("user32.dll")]
        public static extern int SetForegroundWindow(
            int hWnd // handle to window
            );
        private void Form1_Load(object sender, EventArgs e) {
            gkh.HookedKeys.Add(Keys.A);
            gkh.HookedKeys.Add(Keys.B);
            gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
            gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
        }

        void gkh_KeyUp(object sender, KeyEventArgs e) {
            lstLog.Items.Add("Up\t" + e.KeyCode.ToString());
            int iHandle = FindWindow(null, "1 - Notepad");

            SetForegroundWindow(iHandle);

            string keys = "Z";//Here is the keys you want to send.

            System.Windows.Forms.SendKeys.Send(keys);
            e.Handled = true;
        }

        void gkh_KeyDown(object sender, KeyEventArgs e) {
            lstLog.Items.Add("Down\t" + e.KeyCode.ToString());
            e.Handled = true;
        }
    }

效果自己测吧,直接可以改另一个app的触发事件。

时间: 2024-11-13 11:21:35

黑客来了。。。键盘钩子,听起来很高端。的相关文章

浅谈 PHP递归的理解(递归听起来很高端的词汇 其实就是两次循环)

$data = [ ['pid'=>0,'id'=>1], ['pid'=>1,'id'=>2], ['pid'=>3,'id'=>4], ['pid'=>0,'id'=>3], ]; //对上面的数据进行递归排序(原生的写法) function genCate( $data, $pid = 0) { static $result = array(); foreach ($data as $key => $row) { if ($row['pid']

C#实现键盘钩子

前言: 因为项目中需要使用到快捷键,所以上网找资料了解关于快捷键的实现技术,于是有了键盘钩子的使用学习.在网上了解到,键盘钩子其实只是很多种钩子中的其中一种.所谓钩子:请看下面关于钩子的描述(来自百度百科): Windows系统是建立在事件驱动的机制上的,说穿了就是整个系统都是通过消息的传递来实现的.而钩子是Windows系统中非常重要的系统接口,用它可以截获并处理送给其他应用程序的消息,来完成普通应用程序难以实现的功能. 钩子可以监视系统或进程中的各种事件消息,截获发往目标窗口的消息并进行处理

C#全局键盘监听(Hook)的使用

一.为什么需要全局键盘监听? 在某些情况下应用程序需要实现快捷键执行特定功能,例如大家熟知的QQ截图功能Ctrl+Alt+A快捷键,只要QQ程序在运行(无论是拥有焦点还是处于后台运行状态),都可以按下快捷键使用此功能... 这个时候在程序中添加键盘监听肯定不能满足需求了,当用户焦点不在App上时(如最小化,或者用户在处理其它事物等等)键盘监听就失效了 二.怎样才能实现全局键盘监听? 这里需要用到Windows API,源码如下:(可以作为一个工具类[KeyboardHook.cs]收藏起来) u

【转】【C#】全局键盘监听

using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Reflection; namespace 梦琪动漫屋 { /// <summary> /// 键盘钩子/// </summary> class KeyboardHook { public ev

常规鼠标键盘钩子.映像劫持.开机自启动

using System;using System.Collections.Generic;using System.IO;using System.Windows.Forms;using System.Runtime.InteropServices;using System.Reflection; namespace HookTest{ /* 注意: 如果运行中出现SetWindowsHookEx的返回值为0,这是因为.net 调试模式的问题,具体的做法是禁用宿主进程,在 Visual Stu

C#键盘钩子 鼠标钩子

最新对C#模拟键盘按键,鼠标操作产生了兴趣.特从网上收集了一些常用的API用来调用键盘,鼠标操作. class Win32API { #region DLL导入 /// <summary> /// 用于设置窗口 /// </summary> /// <param name="hWnd"></param> /// <param name="hWndInsertAfter"></param> ///

HTML5 键盘监听原理实现的抓怪兽游戏+代码

HTML5小游戏抓怪兽,应用Canvas等超多的HTML5技巧编写而成,下面来向大家汇报实现步骤: 1.创建游戏画布: .代码   var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = 512; canvas.height = 480; document.body.appendChild(canvas); 我们需要做的第一件事是

python之键盘监听木马(SMTP信箱收取监听结果、修改注册表自启动)

最近接触了python的win32库,库子提供了不少可用于windows开发的API,这里就利用这个为原理制作一个键盘监听木马的雏形. 这里需要使用额外的模块pythonHook(放置钩子时),pythoncom 主要监听功能相关代码: #放置键盘监听钩子 def seeing(): PH=pyHook.HookManager() PH.KeyDown=KeyboardEvent PH.HookKeyboard() pythoncom.PumpMessages() #键盘事件 def Keybo

C#鼠标键盘钩子

using System;using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace ICS.Common { /// <summary> /// 这个类可以让你得到一个在运行中程序的所有键盘或鼠标事件 /// 并且引发一个带KeyEventArgs