gpt4 book ai didi

c# - 系统范围的 Windows CBT Hook 无法正常工作

转载 作者:可可西里 更新时间:2023-11-01 09:46:42 27 4
gpt4 key购买 nike

我正在尝试在 Windows 操作系统上挂接 CBT Hook 。我目前使用的是 Windows 7 x64。

我看过很多帖子讨论这个问题,但没有一个能解决我的问题。应用程序运行良好; Hook 已安装,我可以看到一些通知。

实际上出现的问题是应用程序没有收到关于同一台机器上运行的其他进程的 CBT 钩子(Hook)的通知。

该应用程序是用 C# 编写的(使用 Microsoft .NET)。这是一个正在运行的示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsHook
{
class Program
{
[STAThread]
static void Main(string[] args)
{
uint thid = (uint)AppDomain.GetCurrentThreadId();
bool global = true;

mHookDelegate = Marshal.GetFunctionPointerForDelegate(new HookProc(ManagedCallback));

if (global == true) {
mNativeWrapperInstance = LoadLibrary("Native_x64.dll");
thid = 0;
} else {
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
mNativeWrapperInstance = GetModuleHandle(curModule.ModuleName);
}
}

mNativeWrappedDelegate = AllocHookWrapper(mHookDelegate);
mHookHandle = SetWindowsHookEx(/*WH_CBT*/5, mNativeWrappedDelegate, mNativeWrapperInstance, thid);

if (mHookHandle == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());

Application.Run(new Form());

if (FreeHookWrapper(mNativeWrappedDelegate) == false)
throw new Win32Exception("FreeHookWrapper has failed");
if (FreeLibrary(mNativeWrapperInstance) == false)
throw new Win32Exception("FreeLibrary has failed");

if (UnhookWindowsHookEx(mHookHandle) == false)
throw new Win32Exception(Marshal.GetLastWin32Error());
}

static int ManagedCallback(int code, IntPtr wParam, IntPtr lParam)
{
Trace.TraceInformation("Code: {0}", code);
if (code >= 0) {
return (0);
} else {
return (CallNextHookEx(mHookHandle, code, wParam, lParam));
}
}

delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);

static IntPtr mHookHandle;

static IntPtr mHookDelegate;

static IntPtr mNativeWrapperInstance = IntPtr.Zero;

static IntPtr mNativeWrappedDelegate = IntPtr.Zero;

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int hook, IntPtr callback, IntPtr hMod, uint dwThreadId);

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

[DllImport("user32.dll")]
internal static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);

[DllImport("Native_x64.dll")]
private static extern IntPtr AllocHookWrapper(IntPtr callback);

[DllImport("Native_x64.dll")]
private static extern bool FreeHookWrapper(IntPtr wrapper);

[DllImport("Native_x64.dll")]
private static extern int FreeHooksCount();
}

AllocHookWrapper 和 FreeHookWrapper 是从用于 x64 平台的 DLL (Native_x64.dll) 编译器导入的例程,位于应用程序的同一目录中。 AllocHookWrapper 存储(托管例程的)函数指针并返回调用函数指针的 DLL 例程。

这是动态链接库的代码:

#include "stdafx.h"
#include "iGecko.Native.h"

#ifdef _MANAGED
#pragma managed(push, off)
#endif

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#define WRAPPER_NAME(idx) Wrapper ## idx

#define WRAPPER_IMPLEMENTATION(idx) \
LRESULT WINAPI WRAPPER_NAME(idx)(int code, WPARAM wparam, LPARAM lparam) \
{ \
if (sHooksWrapped[idx] != NULL) \
return (sHooksWrapped[idx])(code, wparam, lparam); \
else \
return (0); \
}

#define WRAPPER_COUNT 16

HOOKPROC sHooksWrapped[WRAPPER_COUNT] = { NULL };

WRAPPER_IMPLEMENTATION(0x00);
WRAPPER_IMPLEMENTATION(0x01);
WRAPPER_IMPLEMENTATION(0x02);
WRAPPER_IMPLEMENTATION(0x03);
WRAPPER_IMPLEMENTATION(0x04);
WRAPPER_IMPLEMENTATION(0x05);
WRAPPER_IMPLEMENTATION(0x06);
WRAPPER_IMPLEMENTATION(0x07);
WRAPPER_IMPLEMENTATION(0x08);
WRAPPER_IMPLEMENTATION(0x09);
WRAPPER_IMPLEMENTATION(0x0A);
WRAPPER_IMPLEMENTATION(0x0B);
WRAPPER_IMPLEMENTATION(0x0C);
WRAPPER_IMPLEMENTATION(0x0D);
WRAPPER_IMPLEMENTATION(0x0E);
WRAPPER_IMPLEMENTATION(0x0F);

const HOOKPROC sHookWrappers[] = {
WRAPPER_NAME(0x00),
WRAPPER_NAME(0x01),
WRAPPER_NAME(0x02),
WRAPPER_NAME(0x03),
WRAPPER_NAME(0x04),
WRAPPER_NAME(0x05),
WRAPPER_NAME(0x06),
WRAPPER_NAME(0x07),
WRAPPER_NAME(0x08),
WRAPPER_NAME(0x09),
WRAPPER_NAME(0x0A),
WRAPPER_NAME(0x0B),
WRAPPER_NAME(0x0C),
WRAPPER_NAME(0x0D),
WRAPPER_NAME(0x0E),
WRAPPER_NAME(0x0F)
};

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
return (TRUE);
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

extern "C" IGECKONATIVE_API HOOKPROC WINAPI AllocHookWrapper(HOOKPROC wrapped)
{
for(int i = 0; i < WRAPPER_COUNT; i++) {
if (sHooksWrapped[i] == NULL) {
sHooksWrapped[i] = wrapped;
return sHookWrappers[i];
}
}

return (NULL);
}

extern "C" IGECKONATIVE_API BOOL WINAPI FreeHookWrapper(HOOKPROC wrapper)
{
for(int i = 0; i < WRAPPER_COUNT; i++) {
if (sHookWrappers[i] == wrapper) {
sHooksWrapped[i] = NULL;
return TRUE;
}
}

return (FALSE);
}

extern "C" IGECKONATIVE_API INT WINAPI FreeHooksCount()
{
int c = 0;

for(int i = 0; i < WRAPPER_COUNT; i++) {
if (sHooksWrapped[i] == NULL)
c++;
}

return (c);
}

其实我对某个系统上的窗口相关事件(创建,销毁)很感兴趣,但实际上我无法收到操作系统的通知...

这是怎么回事?我错过了什么?

请注意,我正在与 Administratos 组一起运行。


我在 page 中找到了这个有趣的部分

Global hooks are not supported in the .NET Framework You cannot implement global hooks in Microsoft .NET Framework. To install a global hook, a hook must have a native DLL export to insert itself in another process that requires a valid, consistent function to call into. This behavior requires a DLL export. The .NET Framework does not support DLL exports. Managed code has no concept of a consistent value for a function pointer because these function pointers are proxies that are built dynamically.

我想通过实现一个包含钩子(Hook)回调的 native DLL 来实现这个技巧,它调用托管回调。但是,托管回调仅在调用 SetWindowsHookEx 例程的进程中调用,而不会被其他进程调用。

有哪些可能的解决方法?

也许分配堆内存来存储进程 ID(托管进程 ID),并发送描述 Hook 函数的用户消息?


我想要实现的是一个系统范围的监视器,它检测执行的新进程,检测创建的​​窗口位置和大小,以及关闭的窗口、移动的窗口、最小化/最大化的窗口。随后,监视器应检测鼠标和键盘事件(始终在系统范围内),并且它还必须“模拟”鼠标和键盘事件。

同一桌面上的每个进程都必须由存档(32 位或 64 位)和底层框架( native 或托管)独立监控。

监视器应强制处理窗口的位置、大小和移动,并且应能够充当本地用户,以允许远程用户充当本地用户(类似于 VNC)。

最佳答案

抱歉,我不明白“包装”非托管 DLL 的意义以及将 ManagedCallback 用作托管 EXE 内部的 Hook 的用法。

您应该明白,您用作系统范围 CBT Hook 回调的方法(SetWindowsHookEx 的参数)必须加载到 所有进程 的地址空间中(它将完成对实现 Hook 函数的模块的 DLL 注入(inject))。在 Windows SDK (MSDN) 中,您可以阅读以下内容(参见关于 http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx 的备注):

SetWindowsHookEx can be used to inject a DLL into another process. A 32-bit DLL cannot be injected into a 64-bit process, and a 64-bit DLL cannot be injected into a 32-bit process. If an application requires the use of hooks in other processes, it is required that a 32-bit application call SetWindowsHookEx to inject a 32-bit DLL into 32-bit processes, and a 64-bit application call SetWindowsHookEx to inject a 64-bit DLL into 64-bit processes. The 32-bit and 64-bit DLLs must have different names.

此外,您在有关系统范围 Hook 的问题中写下了 not 0 作为 SetWindowsHookEx 的最后一个参数。还有一个问题:作为 SetWindowsHookEx (HINSTANCE hMod) 的第三个参数,您使用了一个不是带有 Hook 代码的 dll 的实例(您当前拥有的 Hook 代码EXE)。

所以我的建议是:您必须编写新的 native 代码来实现系统范围的 CBT Hook ,并将其放入 DLL 中。我建议您还为 DLL 选择一个基地址(链接器开关),这不是减少 DLL rebase 的标准值。这不是强制性的,但这将节省内存资源。

很抱歉带来坏消息,但我认为您当前的代码应该完全重写。

UPDATED 基于问题的更新:我再重复一次,如果您在一个进程中调用 SetWindowsHookEx 来设置 CBT Hook ,您应该作为参数 DLL 的模块实例(起始地址)和实现 Hook 的 DLL 中函数的地址。从哪个进程调用 SetWindowsHookEx 函数并不重要。用作参数的 DLL 将被加载(注入(inject))到使用 User32.dll 的同一 Windows 站的所有进程中。所以你有一些 native 限制。如果你想同时支持 32 位和 64 位平台,你必须实现两个 dll:一个 32 位和一个 64 位 DLL。此外,在同一进程中使用不同的 .NET 版本也存在问题。理论上只有 .NET 4.0 才可以做到这一点。一般来说,这是一个非常复杂的问题。你应该明白我写的关于 DLL 我的意思是不仅是 DLL,还有它的所有依赖项。因此,如果您实现调用托管 DLL (.NET DLL) 的 native DLL,那将是不可能的。

因此,如果您想使用全局 CBT Hook ,您必须将 if 实现为两个 native DLL(一个 32 位和 64 位)并在两个进程(一个 32 位)中设置安装 Hook 位和 64 位)。因此,请按照 SetWindowsHookEx 文档 http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx 的备注中的描述进行操作。 (见上引)。我看不到更简单的方法。

关于c# - 系统范围的 Windows CBT Hook 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3122215/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com