c#

c# setwindowshookex如何使用

小樊
96
2024-07-16 15:10:52
栏目: 编程语言

在C#中使用SetWindowsHookEx函数可以通过PInvoke进行调用。以下是一个简单的示例代码,演示如何使用SetWindowsHookEx函数来监听并拦截鼠标消息。

using System;
using System.Runtime.InteropServices;

namespace SetWindowsHookExExample
{
    class Program
    {
        private delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        private const int WH_MOUSE_LL = 14;

        private static IntPtr hookId = IntPtr.Zero;
        private static HookProc hookProc;

        static void Main(string[] args)
        {
            hookProc = HookCallback;
            hookId = SetHook(hookProc);

            Console.WriteLine("Hook installed. Press any key to exit...");
            Console.ReadKey();

            UnhookWindowsHookEx(hookId);
        }

        private static IntPtr SetHook(HookProc proc)
        {
            using (var curProcess = System.Diagnostics.Process.GetCurrentProcess())
            using (var curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_MOUSE_LL, proc, Marshal.GetHINSTANCE(curModule), 0);
            }
        }

        private static IntPtr HookCallback(int code, IntPtr wParam, IntPtr lParam)
        {
            // Intercept and handle mouse messages here
            return CallNextHookEx(hookId, code, wParam, lParam);
        }
    }
}

请注意,这只是一个简单的示例,真实的使用可能需要更多的代码来处理不同类型的消息或事件。您可以根据自己的需求修改和扩展以上示例。

0
看了该问题的人还看了