标题:C#键盘hook技术
只看楼主
yuyuyuy
Rank: 2
等 级:论坛游民
帖 子:16
专家分:10
注 册:2019-1-17
结帖率:0
 问题点数:0 回复次数:0 
C#键盘hook技术
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace hook
{
    public partial class Form1 : Form
    {
        //定义句柄变量
        int hwnd = 0;

        //声明MouseProc委托并定义hookCallback变量
        public delegate int MouseProc(int nCode, int wParam, int lParam);
        private MouseProc hookCallback = null;

        //声明win32函数
        [DllImport("user32.dll", EntryPoint = "CallNextHookEx")]
        public static extern int CallNextHookEx(int hHook, int ncode, int Wparam, int lParam);
        [DllImport("user32.dll", EntryPoint = "SetWindowsHookExA")]
        public static extern int SetWindowsHookExA(int idHook, MouseProc lpfn, int hmod, int dwTreadId);
        [DllImport("user32.dll", EntryPoint = "UnhookWindowsHookEx")]
        public static extern int UnhookWindowsHookEx(int hHook);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        public static extern int GetModuleHandle(string lpModuleName);


        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //实例化委托
            this.hookCallback = new MouseProc(HookCallback);
            //获取当前程序句柄
            Process curProcess = Process.GetCurrentProcess();
            ProcessModule curModule = curProcess.MainModule;
            //设置钩子
            hwnd = SetWindowsHookExA(13, hookCallback, GetModuleHandle(curModule.ModuleName), 0);

        }
        private int HookCallback(int nCode, int wParam, int lParam)
        {
            //判断键盘是否按下
            if (wParam == 256 )
            {
                //输出当前按下的键
                MessageBox.Show(Marshal.ReadInt32((IntPtr)lParam));
            }
            //到下一个钩子
            CallNextHookEx(hwnd, nCode, wParam, lParam);
            return 0;
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //释放钩子
            UnhookWindowsHookEx(hwnd);
        }
        
    }
}
搜索更多相关主题的帖子: hwnd System using public int 
2020-12-31 11:26



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-504458-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.360084 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved