首页 > 编程语言 >C# 鼠标hook和键盘hook

C# 鼠标hook和键盘hook

时间:2023-08-22 09:47:51浏览次数:62  
标签:wParam const 鼠标 C# private Keys hook int public

鼠标HOOK

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

namespace ceshi
{
public class MouseHook
{
public event MouseEventHandler onm ouseActivity;

    [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
    public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

    [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
    public static extern bool UnhookWindowsHookEx(int idHook);

    [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
    public static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);

    ~MouseHook()
    {
        this.Stop();
    }

    public void Start()
    {
        if (hMouseHook == 0)
        {
            this.MouseHookProcedure = new HookProc(this.MouseHookProc);
            hMouseHook = SetWindowsHookEx(14, this.MouseHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
            if (hMouseHook == 0)
            {
                this.Stop();
                throw new Exception("SetWindowsHookEx failed.");
            }
        }
    }

    public void Stop()
    {
        bool flag = true;
        if (hMouseHook != 0)
        {
            flag = UnhookWindowsHookEx(hMouseHook);
            hMouseHook = 0;
        }
        if (!flag)
        {
            throw new Exception("UnhookWindowsHookEx failed.");
        }
    }

    private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
    {
        if (nCode >= 0 && this.OnMouseActivity != null)
        {
            MouseButtons button = MouseButtons.None;
            int clicks = 0;
            switch (wParam)
            {
                case 513:
                    button = MouseButtons.Left;
                    clicks = 1;
                    break;
                case 514:
                    button = MouseButtons.Left;
                    clicks = 1;
                    break;
                case 515:
                    button = MouseButtons.Left;
                    clicks = 2;
                    break;
                case 516:
                    button = MouseButtons.Right;
                    clicks = 1;
                    break;
                case 517:
                    button = MouseButtons.Right;
                    clicks = 1;
                    break;
                case 518:
                    button = MouseButtons.Right;
                    clicks = 2;
                    break;
            }
            MouseHookStruct mouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
            MouseEventArgs e = new MouseEventArgs(button, clicks, mouseHookStruct.pt.x, mouseHookStruct.pt.y, 0);
            this.OnMouseActivity(this, e);
        }
        return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
    }

    private const int WM_MOUSEMOVE = 512;
    private const int WM_LBUTTONDOWN = 513;
    private const int WM_RBUTTONDOWN = 516;
    private const int WM_MBUTTONDOWN = 519;
    private const int WM_LBUTTONUP = 514;
    private const int WM_RBUTTONUP = 517;
    private const int WM_MBUTTONUP = 520;
    private const int WM_LBUTTONDBLCLK = 515;
    private const int WM_RBUTTONDBLCLK = 518;
    private const int WM_MBUTTONDBLCLK = 521;

    private static int hMouseHook;
    public const int WH_MOUSE_LL = 14;
    private HookProc MouseHookProcedure;

    [StructLayout(LayoutKind.Sequential)]
    public class POINT
    {
        public int x;
        public int y;
    }

    [StructLayout(LayoutKind.Sequential)]
    public class MouseHookStruct
    {
        public POINT pt;
        public int hWnd;
        public int wHitTestCode;
        public int dwExtraInfo;
    }

    public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
}
}

键盘HOOK

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

namespace ceshi
{
    public class KeyboardHook
    {
        public event KeyEventHandler OnKeyDownEvent;
        public event KeyEventHandler OnKeyUpEvent;
        public event KeyPressEventHandler OnKeyPressEvent;

        public void SetHook()
        {
            this.KeyboardHookDelegate = new Win32Api.HookProc(this.KeyboardHookProc);
            IntPtr moduleHandle = Win32Api.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
            this.hHook = Win32Api.SetWindowsHookEx(13, this.KeyboardHookDelegate, moduleHandle, 0);
        }

        public void UnHook()
        {
            Win32Api.UnhookWindowsHookEx(this.hHook);
        }

        private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam)
        {
            if (nCode >= 0 && (this.OnKeyDownEvent != null || this.OnKeyUpEvent != null || this.OnKeyPressEvent != null))
            {
                Win32Api.KeyboardHookStruct keyboardHookStruct = (Win32Api.KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.KeyboardHookStruct));
                Keys vkCode = (Keys)keyboardHookStruct.vkCode;
                if ((this.OnKeyDownEvent != null || this.OnKeyPressEvent != null) && (wParam == 256 || wParam == 260) && this.IsCtrlAltShiftKeys(vkCode) && this.preKeysList.IndexOf(vkCode) == -1)
                {
                    this.preKeysList.Add(vkCode);
                }
                if (this.OnKeyDownEvent != null && (wParam == 256 || wParam == 260))
                {
                    KeyEventArgs e = new KeyEventArgs(this.GetDownKeys(vkCode));
                    this.OnKeyDownEvent(this, e);
                }
                if (this.OnKeyPressEvent != null && wParam == 256)
                {
                    byte[] array = new byte[256];
                    Win32Api.GetKeyboardState(array);
                    byte[] array2 = new byte[2];
                    if (Win32Api.ToAscii(keyboardHookStruct.vkCode, keyboardHookStruct.scanCode, array, array2, keyboardHookStruct.flags) == 1)
                    {
                        KeyPressEventArgs e2 = new KeyPressEventArgs((char)array2[0]);
                        this.OnKeyPressEvent(this, e2);
                    }
                }
                if ((this.OnKeyDownEvent != null || this.OnKeyPressEvent != null) && (wParam == 257 || wParam == 261) && this.IsCtrlAltShiftKeys(vkCode))
                {
                    for (int i = this.preKeysList.Count - 1; i >= 0; i--)
                    {
                        if (this.preKeysList[i] == vkCode)
                        {
                            this.preKeysList.RemoveAt(i);
                        }
                    }
                }
                if (this.OnKeyUpEvent != null && (wParam == 257 || wParam == 261))
                {
                    KeyEventArgs e3 = new KeyEventArgs(this.GetDownKeys(vkCode));
                    this.OnKeyUpEvent(this, e3);
                }
            }
            return Win32Api.CallNextHookEx(this.hHook, nCode, wParam, lParam);
        }

        private Keys GetDownKeys(Keys key)
        {
            Keys keys = Keys.None;
            foreach (Keys keys2 in this.preKeysList)
            {
                if (keys2 == Keys.LControlKey || keys2 == Keys.RControlKey)
                {
                    keys |= Keys.Control;
                }
                if (keys2 == Keys.LMenu || keys2 == Keys.RMenu)
                {
                    keys |= Keys.Alt;
                }
                if (keys2 == Keys.LShiftKey || keys2 == Keys.RShiftKey)
                {
                    keys |= Keys.Shift;
                }
            }
            return keys | key;
        }

        private bool IsCtrlAltShiftKeys(Keys key)
        {
            return key == Keys.LControlKey || key == Keys.RControlKey || key == Keys.LMenu || key == Keys.RMenu || key == Keys.LShiftKey || key == Keys.RShiftKey;
        }

        private int hHook;
        private Win32Api.HookProc KeyboardHookDelegate;
        private List<Keys> preKeysList = new List<Keys>();
    }
}

 

标签:wParam,const,鼠标,C#,private,Keys,hook,int,public
From: https://www.cnblogs.com/guangzhiruijie/p/17647660.html

相关文章

  • Pixelmator Pro for Mac(媲美PS的修图软件)
    PixelmatorProMac版是一款功能强大的PhotoshopMac版替代品,它能轻松地为照片和视频添加任何更改。它提供了一套革命性的工具,可以帮助您在任何照片,视频或幻灯片上进行更改。所有这些工具都非常快速有效。使用PixelmatorPro,您可以轻松地将照片和视频从普通的Photoshop中提取出......
  • CSharp在Linux上使用Tesseract-OCR
    CSharp在Linux上使用Tesseract-OCR 1主要思路在Linux环境中使用ASP.NETCore调用TesseractOCR引擎可以按照以下步骤进行操作: 1确保你已经在Linux上安装和配置了TesseractOCR引擎。2在你的ASP.NETCore项目中,使用NuGet包管理器或dotnet命令行工具将Tesseract包添加......
  • Luminar Neo mac(超强AI图片编辑器)
    LuminarNeoMac版是一款非常强大的图片编辑软件,LuminarNeomac是一款功能丰富的图片编辑软件,LuminarNeomac强大的AI技术可以让我们在处理照片时获得更好的效果。LuminarNeomac让你可以轻松编辑、调整图像,它可以让你处理所有照片。你还可以从内置的滤镜中选择适合的滤镜,使......
  • LeetCode338.比特位计数
    先以2,3为例,它们的二进制分别是10、11,可以看到,忽略其二进制中最高位的1之后,这组数中二进制位为1的数量分别和数字0,1中二进制位为1的数量相同,再以4,5,6,7为例,他们的二进制分别是100、101、110、111,忽略其二进制中最高位的1之后,这组数中二进制位为1的数量分别和数字0,1,2,3中二进制位为1的......
  • [COCI2011-2012#6] KOŠARE
    Problem有\(N\)个箱子、\(M\)种礼物,第\(i\)个箱子里有\(K_i\)种礼物。需要选出一些箱子,要求每一种礼物至少出现在一个箱子中。求可行的方案数\(mod\)\(10^9+7\)。Input输入第一行,包含正整数\(N(1\leN\le10^6)\)和\(M(1\leM\le20)\)。接下来的\(N\)......
  • WMCTF 2023 Writeup
    WMCTF2023Writeup人刚分手,打个CTF拿3个二血,1个三血,本来还挺高兴的,只有一血有奖励。好好好,都欺负我是吧。ezAndroiduserName是一个类似RC4的东西,直接复制出来跑,password是变表AES,在.init_array修改了AES的sbox。#include<stdio.h>#include<stdint.h>#include......
  • 【6.0】爬虫之scrapy框架
    【一】Scrapy框架基本介绍【1】Scrapy一个开源和协作的框架其最初是为了页面抓取(更确切来说,网络抓取)所设计的,使用它可以以快速、简单、可扩展的方式从网站中提取所需的数据。但目前Scrapy的用途十分广泛,可用于如数据挖掘、监测和自动化测试等领域,也可以应用在获取API所......
  • tensorflow模型训练保存minist OCR
    importtensorflowastffromtensorflow.python.framework.convert_to_constantsimportconvert_variables_to_constants_v2fromtensorflow.python.toolsimportoptimize_for_inference_libimportnumpyasnpimportmatplotlib.pyplotaspltimportdatetimeimpor......
  • async/await
    async/await是同步语法,能以不使用回调函数的方式来实现异步。await被async包裹,await后面可以追加Promise对象,也可以追加async函数。执行async函数,返回的是一个Promise对象。如果直接返回一个值,那么会把这个值封装成一个Promise对象。await相当于Promise的then。 优点:1.方便......
  • JSONObject.toJavaObject
    YgCompanyygCompany=JSONObject.toJavaObject(json,YgCompany.class);这段代码使用了阿里巴巴的fastjson库中的JSONObject.toJavaObject()方法,将JSON字符串转换为Java对象。具体解释如下:1.JSONObject是fastjson库中的一个类,用于处理JSON对象。2.toJavaObject()是JSONObje......