HOOK

/**
*Environment : VS2005
*/

DLL:
File name:HookDll.ccp


=============================================
#include <windows.h>
#include "string.h"
#include "stdio.h"

HINSTANCE hInst;

#pragma data_seg("hookdata")
HHOOK oldkeyhook=0;
#pragma data_seg()

#pragma comment(linker,"/SECTION:hookdata,RWS")

#define DllExport extern "C"__declspec(dllexport)
void writeFile1(char *msg);
DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam, LPARAM lParam );
DllExport void InstallHook(int nCode);
DllExport void EndHook(void);

BOOL WINAPI DllMain(HINSTANCE hInstance,ULONG What,LPVOID NotUsed)
{
switch(What)
{
case DLL_PROCESS_ATTACH:
hInst = hInstance;
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;

}
return 1;
}

void InstallHook(int nCode)
{
oldkeyhook = SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyBoardProc,hInst,0);
}

DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam, LPARAM lParam )
{
    /*
    WPARAM j;
    FILE *fp;
    errno_t err;
    if(lParam&0x80000000)
    {
        j = wParam;
        err=fopen_s(&fp,"c:\hookkey.txt","a");
        fprintf(fp,"%4d",j);
        fclose(fp);
    }
    */
    writeFile1("callback function invoked");
    return CallNextHookEx(oldkeyhook,nCode,wParam,lParam);
}
void EndHook(void)
{
UnhookWindowsHookEx(oldkeyhook);
}
void writeFile1(char *msg){

     FILE *fp;
     fp=fopen("C:/test1.txt","a");
     fputs(msg,fp);
     fputs("\n",fp);
     fclose(fp);

}

=================================================
testing
File name:hookTest.ccp

=================================================


#include "stdio.h"
#include <windows.h>

void main(void)
{

    typedef void(*installHook)(int ncode);
    typedef void(*killHook)(void);
    HINSTANCE hDLL; installHook iHook; killHook kHook;
    hDLL=LoadLibrary(TEXT("hookdll2.dll"));
    if(hDLL!=NULL){
        MessageBox (NULL, TEXT ("Hello, Windows 00000000000!"), TEXT ("HelloMsg"), 0);
        iHook=(installHook)GetProcAddress(hDLL,"InstallHook");
        kHook=(killHook)GetProcAddress(hDLL,"EndHook");
        if(iHook){
            MessageBox (NULL, TEXT ("Hello, Windows 11111111111111!"), TEXT ("HelloMsg"), 0);
            iHook(0);
        }
        if(kHook){
            MessageBox (NULL, TEXT ("Hello, Windows 2222222222222222!"), TEXT ("HelloMsg"), 0);
            kHook();
        }
        FreeLibrary(hDLL);
    }

}

你可能感兴趣的:(OO)