Windows 7中的全局CBT Hook最终失败

时间:2013-04-09 00:40:13

标签: c# c++ winapi hook global

我正在使用全局CBT挂钩设置来阻止新窗口窃取焦点。我正在从c#app注入c ++ DLL。它运行良好一段时间然后停止工作。我认为它可能会超时,但我在注册表中更改了我的LowLevelHooksTimeout并重新启动。这没有用。

我对c ++并不是那么好。所以,也许这是我的代码中的一个错误。什么可能导致它失败?另外,有没有办法处理名称修改和清理该代码?

WindowMonitor.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;
 }

WindowMonitor.h

#ifndef WM
#define WM
extern "C" {

#define DLLEXPORT  __declspec(dllexport)
  DLLEXPORT bool InjectCBTHook() ;
  DLLEXPORT bool EjectCBTHooks();
}

#endif 

C#P / Invoke

[DllImport("WindowMonitor.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool InjectCBTHook();
[DllImport("WindowMonitor.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool EjectCBTHooks();

0 个答案:

没有答案