2008年7月15日 星期二

Check Keyboard & Mouse Hook #2

寫全局鉤子
鎖定鍵盤和鼠標的鉤子
DLL端
// HOOK.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "HOOK.h"
#include "mmsystem.h"


#define _WIN32_WINNT 0x0500

#include
#include


HINSTANCE hInstance;
HHOOK hhkKeyboard;
HHOOK hhMouseHook;

BOOL APIENTRY DllMain( HANDLE 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;
}
hInstance=(HINSTANCE)hModule;
return TRUE;
}


// This is an example of an exported variable
HOOK_API int nHOOK=0;

// This is an example of an exported function.
HOOK_API int fnHOOK(void)
{
return 42;
}

// This is the constructor of a class that has been exported.
// see HOOK.h for the class definition
CHOOK::CHOOK()
{
return;
}

LRESULT LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
//可以加入一些釋放鍵盤的代碼

}

LRESULT LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
//可以加入一些釋放鼠標的代碼
}

HOOK_API BOOL EnableKeyboardCapture()//設定鉤子用來鎖定鍵盤鼠標
{
if (!(hhkKeyboard=SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)LowLevelKeyboardProc, hInstance, 0)))
return FALSE;
if (!(hhMouseHook=SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)LowLevelMouseProc, hInstance, 0)))
return FALSE;;
return TRUE;
}

HOOK_API BOOL DisableKeyboardCapture()//釋放鍵盤和鼠標
{
UnhookWindowsHookEx(hhMouseHook);
return UnhookWindowsHookEx(hhkKeyboard);
}





###################################################################


DLL端編譯器(VC6)C/C++屬性頁加入環境變量HOOK_EXPORTS
//頭文件定義
HOOK.h
------------------------------------------------------------
#ifdef HOOK_EXPORTS
#define HOOK_API __declspec(dllexport)
#else
#define HOOK_API __declspec(dllimport)
#endif

HOOK_API BOOL EnableKeyboardCapture();
HOOK_API BOOL DisableKeyboardCapture();
// This class is exported from the HOOK.dll
class HOOK_API CHOOK {
public:
CHOOK(void);
// TODO: add your methods here.
};

extern HOOK_API int nHOOK;

HOOK_API int fnHOOK(void);



應用程序端只要加入HOOK.H和HOOK.lib就行了,然後按自己要求調用

EnableKeyboardCapture();
DisableKeyboardCapture();

最後提醒一句,在沒有加入釋放鍵盤鼠標的代碼前,不要編譯運行,否則後果自負

沒有留言: