我一直试图在Visual C ++中创建一个全局键盘挂钩程序,该程序在文件“ log.txt”中写入击键。.我是Windows编程的新手,我已经通过msdn库来了解挂钩。我想我从理论上理解了这个概念,但是当我实现代码时,它是行不通的。编译器在DLL文件和EXE文件中均未显示任何错误。被创建...
这是代码文件

第一个DLL文件:

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

HHOOK g_hhk;

__declspec(dllexport) LRESULT CALLBACK KeyProc(int nCode, WPARAM wParam, LPARAM lParam)
{
        if(nCode>=0)
         {
          char ch;
         FILE *fp;
         fp=fopen("log.txt","a");
         if((wParam==VK_SPACE)||(wParam==VK_RETURN)||(wParam>=0x2f ) &&(wParam<=0x100))
         {
         if(wParam==VK_RETURN)
        ch='\n';
        fwrite(&ch,1,1,fp);
    }
    else
    {
        BYTE ks[256];
        GetKeyboardState(ks);

        WORD w;

        UINT scan;

        scan=0;

        ToAscii(wParam,scan,ks,&w,0);

        ch =char(w);

        fwrite(&ch,1,1,fp);  // copy character to log file
    }
    fclose(fp);
    }
       return CallNextHookEx(g_hhk, nCode, wParam, lParam);
       }

Now the EXE file:

    #include<windows.h>

HOOKPROC hkprckb;
static HINSTANCE hinstDLL;
static HHOOK hhookkb;

int WINAPI WinMain(HINSTANCE hInstance1,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
    hinstDLL=LoadLibrary(TEXT("C:\\Documents and Settings\\Attar Singh\\My Documents\\Visual Studio 2008\\Projects\\key\\Debug\\key.dll"));
    hkprckb=(HOOKPROC)GetProcAddress(hinstDLL,"KeyProc");
    hhookkb=SetWindowsHookEx(
                    WH_KEYBOARD_LL,
                    hkprckb,
                    hinstDLL,
                    0);


    MessageBox(NULL,NULL,NULL,MB_OK);
    return 1;
}


这个程序给我带来了噩梦...任何帮助将不胜感激...谢谢提前...

最佳答案

wParam应该具有以下值之一:
WM_KEYDOWNWM_KEYUPWM_SYSKEYDOWNWM_SYSKEYUP

要获取按键的虚拟按键代码,您必须使用:((KBDLLHOOKSTRUCT*)lParam)->vkCode

关于c++ - 全局键盘 Hook 不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6882854/

10-16 11:20