I want to write a program in C that disables the entire keyboard but continues to receive inputs in my program.
I tried using BlockInput()
, but it also blocks the mouse, and my program can't get the keyboard input.
In other words, I want to capture keyboard events and disable them before they are processed by other programs.
For example:
When I'm running my program and try to write in my browser/notepad, nothing will be shown (like the keyboard is not working), but I can still be able to write to a file what the user wrote.
Is this possible?
In addition to the need to use hooks in the comments, you also need to simulate the string output to the console based on the virtual key code. And You need to detect whether the focus of the mouse is on the notepad or browser.
Here is a code sample:
#include <Windows.h>
#include <iostream>
using namespace std;
HHOOK keyboardHook;
LRESULT __stdcall KEYHookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
int num[] = { 0x41,0x42,0x43,0x44 ,0x45 ,0x46 ,0x47 ,0x48 ,0x49 ,0x4A ,0x4B ,0x4C ,0x4D ,0x4E ,0x4F,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,0x58,0x59,0x5A,0x20};
const char *ch[] = { "A","B", "C", "D", "E", "F", "G", "H","I", "J", "K", "L", "M", "N",
"O","P", "Q", "R", "S", "T", "U" ,"V","W", "X", "Y", "Z"," "};
if (nCode >= 0)
{
switch (wParam)
{
case WM_KEYDOWN:
{
HANDLE stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD written = 0;
KBDLLHOOKSTRUCT* kbdStruct = (KBDLLHOOKSTRUCT*)lParam;
if (stdOut == NULL || stdOut == INVALID_HANDLE_VALUE)
{
cout << "error handle" << endl;
return 0;
}
POINT pntCurrentCursor;
GetCursorPos(&pntCurrentCursor);
HWND h = FindWindow("Notepad", NULL);
HWND h2 = FindWindowEx(h, 0, "Edit", NULL);
HWND h1 = WindowFromPoint(pntCurrentCursor);
if(h1 == h2)
{
for (int i = 0; i < sizeof(num) / sizeof(int); i++)
{
if (kbdStruct->vkCode == num[i])
{
WriteConsole(stdOut, ch[i], 1, &written, NULL);
}
}
}
return 1;
}
}
}
return CallNextHookEx(keyboardHook, nCode, wParam, lParam);
}
void SetHook()
{
if (!(keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KEYHookCallback, NULL, 0)))
{
cout << "Failed to install keyboardHook hook!" << endl;
}
}
void ReleaseHook()
{
UnhookWindowsHookEx(keyboardHook);
}
int main()
{
SetHook();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
ReleaseHook();
return msg.wParam;
}
Debug: