I am trying to write a macro program in C and I have managed to get the keys with the following code:
#include <windows.h>
#include <stdio.h>
HHOOK _hook;
KBDLLHOOKSTRUCT kbdStruct;
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
printf("Key %lu pressed.\n", kbdStruct.vkCode);
} else if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) {
printf("Key %lu released.\n", kbdStruct.vkCode);
}
}
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void main() {
if (!(_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0))) {
MessageBox(NULL, "Failed to install hook!", "Error", MB_ICONERROR);
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {}
}
I want the program to press a sequence of keys on specific times with SendInput()
function when a specific key is pressed.
The WH_KEYBOARD_LL
hook is not called anymore when the while loop is set to infinite.
Also using GetMessage(&msg, NULL, 0, 0)
does not seem to be clean to me.
I have searched for a hook method to call a function on a given interval but without success.
I use the GNU GCC compiler.
I have almost no experience in programming in C on the computer but I do have experience in programming in C for microcontrollers.
Edit:
I have tried the method with SetTimer() but it does not get called. I have used the example from this page: http://www.equestionanswers.com/vcpp/set-timer.php
#include <windows.h>
#include <stdio.h>
#define TimerID 85
HHOOK _hook;
KBDLLHOOKSTRUCT kbdStruct;
VOID __stdcall MyTimerProc(HWND hWnd, UINT uMsg, UINT idEvent, DWORD dwTime) {
printf("Timer call\n");
}
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
printf("Key %lu pressed.\n", kbdStruct.vkCode);
} else if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) {
printf("Key %lu released.\n", kbdStruct.vkCode);
}
}
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void main() {
if (!(_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0))) {
MessageBox(NULL, "Failed to install hook!", "Error", MB_ICONERROR);
}
SetTimer(NULL, TimerID, 1000, MyTimerProc);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {}
}