C#开发键盘按键记录程序(源码)

首先新建一个项目,然后新建类HookUtil,代码如下


using System.Runtime.InteropServices;
using System.Windows.Forms;
using System;

public class HookUtil
{
    #region windows api

    /// <summary>
    /// 安装钩子
    /// </summary>
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
    public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);

    /// <summary>
    /// 继续下一个钩子
    /// </summary>
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);

    /// <summary>
    /// 卸载钩子
    /// </summary>
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern bool UnhookWindowsHookEx(int idHook);

    /// <summary>
    ///获取当前线程编号(线程钩子需要用到)
    [DllImport("kernel32.dll")]
    static extern int GetCurrentThreadId();

    /// <summary>
    /// 获取当前实例的函数
    /// </summary>
    [DllImport("kernel32.dll")]
    public static extern IntPtr GetModuleHandle(string name);


    /// <summary>
    /// 获取按键的状态
    /// </summary>
    /// <param name="pbKeyState"></param>
    /// <returns></returns>
    [DllImport("user32")]
    public static extern int GetKeyboardState(byte[] pbKeyState);

    /// <summary>
    /// 将指定的虚拟键码和键盘状态翻译为相应的字符或字符串
    /// </summary>
    [DllImport("user32")]
    public static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
    #endregion

    /// <summary>
    /// 键盘结构
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public class KeyboardHookStruct
    {
        public int vkCode;  //定一个虚拟键码。该代码必须有一个价值的范围1至254
        public int scanCode; // 指定的硬件扫描码的关键
        public int flags;  // 键标志
        public int time; // 指定的时间戳记的这个讯息
        public int dwExtraInfo; // 指定额外信息相关的信息
    }

    //定义为键盘钩子
    public int WH_KEYBOARD_LL = 13;

    //相关键盘事件
    public event KeyEventHandler KeyDownEvent;
    public event KeyPressEventHandler KeyPressEvent;
    public event KeyEventHandler KeyUpEvent;

    //相关动作
    private const int WM_KEYDOWN = 0x100;//KEYDOWN
    private const int WM_KEYUP = 0x101;//KEYUP
    private const int WM_SYSKEYDOWN = 0x104;//SYSKEYDOWN
    private const int WM_SYSKEYUP = 0x105;//SYSKEYUP

    //hookid
    private int hookID = 0;

    //向下传递数据
    public Keys NoNextKeyCode;

    /// <summary>
    /// 安装钩子
    /// </summary>
    public void StartHook()
    {
        if (hookID == 0)
        {
            HookProc hookProc = new HookProc(KeyboardHookProc);
            hookID = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName), 0);

            if (hookID == 0)
            {
                StopHook();
                throw new Exception("安装键盘钩子失败");
            }
        }
    }


    public void StopHook()
    {
        bool isStop = true;
        if (hookID != 0)
        {
            isStop = UnhookWindowsHookEx(hookID);
            hookID = 0;
        }
        if (!isStop) throw new Exception("卸载键盘钩子失败!");
    }

    /// <summary>
    /// 监听事件
    /// </summary>
    private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
    {
        if ((nCode >= 0) && (KeyDownEvent != null || KeyUpEvent != null || KeyPressEvent != null))
        {

            KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));

            //按下处理
            if (KeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
            {
                Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                KeyEventArgs e = new KeyEventArgs(keyData);
                KeyDownEvent(this, e);
                //阻止向下传递
                if (NoNextKeyCode == keyData)
                {
                    return hookID;
                }
            }

            //按下并抬起处理
            if (KeyPressEvent != null && wParam == WM_KEYDOWN)
            {
                byte[] keyState = new byte[256];
                GetKeyboardState(keyState);

                byte[] inBuffer = new byte[2];
                if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1)
                {
                    KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
                    KeyPressEvent(this, e);
                }
            }

            // 抬起处理
            if (KeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
            {
                Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                KeyEventArgs e = new KeyEventArgs(keyData);
                KeyUpEvent(this, e);
            }

        }
        return CallNextHookEx(hookID, nCode, wParam, lParam);
    }

    ~HookUtil()
    {
        StopHook();
    }
}


在需要开启和停止监控的地方调用如下代码:

HookUtil keyHook = new HookUtil();   //定义全局变量

//在需要监听键盘的地方调用以下代码
keyHook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);//钩住按下事件
keyHook.StartHook();

private void hook_KeyDown(object sender, KeyEventArgs e)
        {
            MessageBox.Show("你刚刚按下了:"+e.KeyData.ToString());
        }

//在需要停止监控键盘按键的地方调用以下代码
keyHook.StopHook();


  1. 本网站所收集的部分资料来源于互联网,本站不对其真实性负责,也不构成任何其他建议。如果您发现有侵犯您权益的内容,请与我们取得联系,我们会及时修改或删除。
  2. 传递知识、传递力量,欢迎各位网友对本站的文章进行转载和分享。
  3. 本站QQ群交流群:904314688  群号:904314688
发表评论
 
评论列表(目前共有 条评论)
暂时还没有评论哦~

文章搜索

商家广告


版权所有:秋风雅居 (www.198933.com) ©2024 All Rights Reserved.

粤ICP备20031662号