另类键盘钩子 DLL自己安装钩子

#pragma data_seg ()

            static HHOOK g_hKeyboardHook = NULL;

            static HINSTANCE g_hInst        = NULL;

#pragma data_seg ()

#pragma comment (linker, "/section:Shared, rws")



BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved) {

     switch(fdwReason){

       case DLL_PROCESS_ATTACH:

       g_hInst =      (HINSTANCE) hInstance; 

。。。。。

然后再用2个输出函数:一个安装钩子,一个卸载钩子

MY_API BOOL HookKey ()

{

       ....

       g_hKeyboardHook     = ::SetWindowsHookEx(WH_KEYBOARD, KeyboardProc,     g_hInst,     NULL);

       ....

}

CreateRemoteThread 去调用安装钩子的导出函数

 

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)

{

BOOL bKeyUp = lParam & (1 << 31);//防止,键盘按和弹起都执行一次

if (bKeyUp && wParam == VK_HOME && nCode == HC_ACTION) {

  

//////////////////////加入窗体////////////////////////////////////////////////////

  

   //AfxMessageBox("ok");



   if (myform == NULL) 

   {

    AFX_MANAGE_STATE(AfxGetStaticModuleState());

    CWnd *pCWnd = CWnd::GetForegroundWindow();

    myform = new CMyForm();

    myform->Create(IDD_MYFORM,pCWnd);

    myform->ShowWindow(SW_SHOW);

   }

   else

   {

    myform->ShowWindow(myform->IsWindowVisible() ? SW_HIDE : SW_SHOW);

   }





   //////////////////////////////////////////////////////////////////////////

}

return ::CallNextHookEx(g_hhook, nCode, wParam ,lParam);

}



extern "C" __declspec(dllexport) BOOL WINAPI InstallHook(HWND h)

{

if (g_hhook == NULL) {

   DWORD pmod;

   DWORD hThread = GetWindowThreadProcessId(h,&pmod);

   g_hhook = ::SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc,theApp.m_hInstance,hThread);

   if (g_hhook != NULL)

    return TRUE;

}

return FALSE;

}



extern "C" __declspec(dllexport) BOOL WINAPI InstallHook(HWND h)

{

if (g_hhook == NULL) {

   DWORD pmod;

   DWORD hThread = GetWindowThreadProcessId(h,&pmod);

   g_hhook = ::SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc,theApp.m_hInstance,hThread);

   if (g_hhook != NULL)

    return TRUE;

}

return FALSE;

}

 

 

 

 

 

 

你可能感兴趣的:(dll)