我正在使用全局 CBT 挂钩设置来阻止新窗口窃取焦点。我正在从 ac# 应用程序注入 c++ DLL。它可以正常运行一段时间,然后停止工作。我认为它可能会超时,但我在注册表中更改了 LowLevelHooksTimeout 并重新启动。那没有帮助。
我对 C++ 不是很好。所以,也许这是我的代码中的一个错误。什么可能导致它失败?另外,有没有办法处理名称修改并稍微清理一下代码?
窗口监视器.cpp
#include <map>
#include "stdafx.h"
#include "header.h"
using namespace std;
#pragma data_seg(".TEST")
HHOOK hook=0;
#pragma data_seg()
#pragma comment(linker, "/section:.TEST,rws")
extern "C"
{
__declspec(dllexport) LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode<=0) return CallNextHookEx(hook, nCode, wParam, lParam);
if (nCode==HCBT_ACTIVATE)
{
try {
CBTACTIVATESTRUCT* stuff=(CBTACTIVATESTRUCT*) lParam;
if (stuff!=0)
{
if (stuff->fMouse==TRUE)
{
return 0;
}
if (stuff->fMouse==FALSE)
{
return 1;
}
}
}
catch (exception& e)
{
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
bool InjectCBTHook()
{
HMODULE hDll;
HOOKPROC cbtProcAddr;
DWORD proc_id;
hDll = LoadLibraryA("WindowMonitor.dll");
cbtProcAddr = (HOOKPROC)GetProcAddress(hDll, "_CBTProc@12");
hook=SetWindowsHookEx(WH_CBT, cbtProcAddr, hDll, 0);
if (hook==0)
{
int x=GetLastError();
return FALSE;
}
return TRUE;
}
bool EjectCBTHooks()
{
UnhookWindowsHookEx(hook);
return TRUE;
}
窗口监视器.h
#ifndef WM
#define WM
extern "C" {
#define DLLEXPORT __declspec(dllexport)
DLLEXPORT bool InjectCBTHook() ;
DLLEXPORT bool EjectCBTHooks();
}
#endif
C# P/调用
[DllImport("WindowMonitor.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool InjectCBTHook();
[DllImport("WindowMonitor.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool EjectCBTHooks();